Quick question on this point:
Code:
Convert.ToWhatever(input);
So I can also use it as in the following statements...
Code:
Convert.ToShort(Console.ReadLine());
Code:
Convert.ToDouble(Console.ReadLine());
Exactly, you can convert it to whatever you like in that way.
I have also just come across another example of a workaround using this method here >>
C# Tutorial
Code:
number2 =int.Parse(Console.ReadLine());
Is there a good or bad way of practice, or is it simply down to the person writing the program?
Both work fine. In actual fact, float.Parse(
input); may actually have been slightly better here, although the difference is small. Basically, here are the differences:
Firstly, .Parse() and .TryParse() only accept strings as input, whereas Convert.To
Whatever will take almost anything (technically, any class which implements the interface
IConvertible, but you don't need to worry about that for now). Therefore, if you are trying to convert anything which isn't a string (maybe from one number format to another which can't be casted, then you must use Convert.To
Whatever, as you have no choice in the matter). Here, however, you
are using a string, so there is still a choice.
There is also a change in functionality. If
input is
null, .Parse() will throw an ArgumentNullException, whereas Convert.To...() will return 0. So you need to make a choice there if this is important to you.
However, there is another consideration with .Parse(). Handing exceptions with try{} catch{} is incredibly slow. When you ask a user for input, it is quite likely that they won't type a pure integer. Thus, first checking with the much faster .TryParse(); may be quicker in the long run, as it bypasses the slow exception handling. But then again, both would be done in less than human reaction time, and you are not running thousands in order to notice a difference.
Therefore, .TryParse() first may be faster. If, however, you don't envisage any exceptions happening often (maybe another part of your program is providing the data, and you can't see why it wouldn't provide a perfect integer), then bypassing .TryParse() and leaving it to exceptions will be faster.
Convert.To...() will be the slowest, as it has to do type checking and null string checking, and then it just calls int/float.Parse() under the hood for a string. But it is convenient.
Probably just ignore all this and decide based on null string handling.
Another quick tip, it is often a good idea to .Trim() strings to remove any whitespace. This is not so important in console application input reading, but elsewhere it is important. I am sure you already know, but just in case:
Code:
Console.ReadLine().Trim();
Richard