xxxxxxxxxx
var myInt = int.Parse("123"); // this one throw exception if the argument is not a number
var successfullyParsed = int.TryParse("123", out convertedInt); //this returns true if the convertion has been successfully done (integer is stored in "convertedInt"), otherwise false.
xxxxxxxxxx
string str = "10s";
int x = Convert.ToInt32(str);
Console.WriteLine(x);
xxxxxxxxxx
string str = "100";
int x = Int32.Parse(str); // or int.Parse();
Console.WriteLine(x);
In C#, you can convert a string to an integer using the int.Parse() or int.TryParse() method.
Here is an example of using int.Parse():
xxxxxxxxxx
string strNum = "123";
int num = int.Parse(strNum);
//And here is an example of using int.TryParse():
string strNum = "123";
int num;
if (int.TryParse(strNum, out num))
{
// The conversion was successful and the value of num is set
}
else
{
// The conversion failed and the value of num is 0
}
Note that int.Parse() will throw an exception if the string cannot be converted to an integer, while int.TryParse() returns a boolean indicating whether the conversion was successful or not, without throwing an exception.
xxxxxxxxxx
// Ask user for fave number
Console.Write("Enter your favorite number!: ");
// Turn that answer into an int
int faveNumber = Convert.ToInt32(Console.ReadLine());
xxxxxxxxxx
Int16.Parse("100"); // returns 100
Int16.Parse("(100)", NumberStyles.AllowParentheses); // returns -100
int.Parse("30,000", NumberStyles.AllowThousands, new CultureInfo("en-au"));// returns 30000
int.Parse("$ 10000", NumberStyles.AllowCurrencySymbol); //returns 100
int.Parse("-100", NumberStyles.AllowLeadingSign); // returns -100
int.Parse(" 100 ", NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite); // returns 100
Int64.Parse("2147483649"); // returns 2147483649
xxxxxxxxxx
string userInput = Console.ReadLine();
int convert;
Int32.TryParse(userInput, out convert); // Converting String to int