Click here to Skip to main content
16,021,765 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Practice
{
class Program
{
static void Main(string[] args)
{
Console.Write("Hi, What is your name? ");
string name = Console.ReadLine();
Console.WriteLine("Hi, " + name);


Console.Write("How old are you? ");
int age = Console.ReadLine();
Console.WriteLine("Cool! I am two years older than you. I am " + age + 2 +".");

Console.ReadLine();

What I have tried:

int age = Console.ReadLine();


above^^^ keeps giving me an error message of...

Cannot implicitly convert type 'string' to 'int'


Why?
Posted
Updated 12-Apr-19 10:37am

Well, you found your problem: int age = Console.ReadLine();
If you read the documentation you will see that this returns a string.
Console.ReadLine Method[^]

The cure for this would be to tweak the line and then do some testing.
int age = (int)Console.ReadLine();

Now you should try some text in there and see the exception it throws. Then you tweak it some more and respond appropriately. How-about a TryParse
C#
int age;
string entry = Console.ReadLine();
if (!int.TryParse(entry, out age)) {
  Console.WriteLine("Please enter a number");
} else {
  Console.WriteLine("Cool! I am two years older than you. I am " + age + 2 +".");
}
It's all up to you
 
Share this answer
 
C# is a strongly typed language. You can not assign a string value to an int variable. You need to CAST (convert data from one type to another) that string to the int value:

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/how-to-convert-a-string-to-a-number
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900