-1

I'm new to c# so forgive me, but I'm just wanting to know why do I have to convert int to int32?

For example I declare lowerRange as an int, but then later on when I am to read user input, I have to convert it to int32 otherwise it gives me an error saying I "cannot implicitly convert type 'string' to 'int'.

OR I'm assuming that I have to convert because the user is entering a string and I have to convert it to an int, which in that case makes me wonder why I have to declare lowerRange as an int the first place?

int lowerRange;
...
lowerRange = Convert.ToInt32(Console.ReadLine());
oneman
  • 811
  • 1
  • 13
  • 31
  • `int` has number characteristics. you can do numeric operations on `int` while that is not possible on `string`, yes user input is string. – M.kazem Akhgary Mar 19 '17 at 05:16
  • "why do I have to convert int to int32" - it is not really possible to answer this question because they are different names for the same type and you can't express conversion between them in C#... Converting string to int on other hand is covered in on or two hundreds of questions... – Alexei Levenkov Mar 19 '17 at 07:35

2 Answers2

8

The Console.ReadLine() method returns a string that needs to be parsed and converted to an integer (using Convert.ToInt32) if you want to assign it to the lowerRange integer variable.

So basically you have this:

int lowerRange;
...
string userInput = Console.ReadLine();
lowerRange = Convert.ToInt32(userInput);

Also notice that the reason why the ReadLine method returns a string is because the user can enter anything as input. So you might want to validate that the user has entered a valid number using the TryParse method, otherwise the ToInt32 method will throw an exception:

string userInput = Console.ReadLine();
if (int.TryParse(userInput, out lowerRange))
{
    // The user entered a valid integer you can use the lowerRange variable here
}
else
{
    Console.WriteLine("Please enter a valid number");
}
Sirwan Afifi
  • 10,654
  • 14
  • 63
  • 110
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • I would be a bit conservative using `TryParse` because it will return a `0` if non-valid string was entered which might lead to unexpected behavior if `0` meant something in the upcoming stages. Using `try`/`catch` gives you more control on what to do. – Everyone Mar 19 '17 at 07:42
0

I have to convert it to int32 otherwise it gives me an error saying I "cannot implicitly convert type 'string' to 'int'.

Because Console.Readline() return string which is from user input.

OR I'm assuming that I have to convert because the user is entering a string and I have to convert it to an int, which in that case makes me wonder why I have to declare lowerRange as an int the first place?

You don't need to declare lowerRange as an integer IF you want to use it as a string. But if you want to use it as a integer then you need to convert it (using Convert class).

Hung Cao
  • 3,130
  • 3
  • 20
  • 29