+ 1
Why do we use the Convert.ToXXX command?
I was experimenting with the convert.readline command and saw that the results from the convert.ToInt32 command and convert.readline commands were the same I just had to change the variable type from int to string.... so why do we use the convert.toxxx command
3 Answers
+ 10
I believe you're talking about the Console.ReadLine method. In most programming languages, user input is always in string.
Therefore if we need to read other data types, we will need to read it as string first and convert afterwards.
For example,
int num = Convert.ToInt32(Console.ReadLine());
Hopefully it helps! š
+ 4
You have to use it because the ReadLine() method returns a string, but you cannot assign a string to a variable with a data type different from string. So, in order to be able to assign the input to variables with other data types aswell, you first have to explicitly cast the returned string to the data type of the variable.
+ 1
A short note: even though the function of Convert.ToXx..() method is to convert the given string input to desired type. there is a chance of FormatException if the given string is not convertible to the destination type. so I will always prefer .TryParse() instead to avoid that exception. which will give the converted value in the out parameter as well as returns a Boolean value indicating the conversion result. for example, accepting an integer value from the console will be like the following.
int input;
if(int.TryParse(Console.ReadLine(), out input))
{
Console.WriteLine("valid");
}
else
{
Console.WriteLine("invalid input");
// input will be 0
}