How to convert the string input taken using Console.ReadLine() function in a C# code??? Suppose I have created 2 integer variables a and b. Now I want to take from user the values of a and b. How can this be performed in C#?
7 Answers
Another option, that I usually use is int.TryParse
int retunedInt;
bool conversionSucceed = int.TryParse("your string", out retunedInt);
so it's good fit for fault tollerant pattern like:
if(!int.TryParse("your string", out retunedInt))
throw new FormatException("Not well formatted string");
3 Comments
TryParse for your second reason but I see that a program may have custom exceptions and logging which would be useful. Just making sure I hadn't missed some secret TryParse usage :DYou can use it with Int32.TryParse();
Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded.
int i;
bool b = Int32.TryParse(yourstring, out i);
Comments
Try this (make sure they input valid string):
int a = int.Parse(Console.ReadLine());
Also this:
int a;
string input;
do
{
input = Console.ReadLine();
} while (!int.TryParse(input, out a));
1 Comment
int.TryParse is you are not sure the input is a string and you want to avoid the exception.You can use Convert.ToInt32():
Convert.ToInt32(input);
Or TryParse()
bool success = Int32.TryParse(value, out number);
Comments
You can use int.TryParse
int number;
bool result = Int32.TryParse(value, out number);
The TryParse method is like the Parse method, except the TryParse method does not throw an exception if the conversion fails. It eliminates the need to use exception handling to test for a FormatException in the event that s is invalid and cannot be successfully parsed. Reference
int.Parse()msdn.microsoft.com/en-gb/library/b3h1hf19.aspx. What have you tried?