
The Convert type provides methods that implement conversions. How can you convert a string to a 32-bit integer using the Convert.ToInt32 method? And how is this different from int.Parse?
This C# program uses the Convert.ToInt32 method from the System namespace.
This program shows how you can convert a string to an int using the Convert.ToInt32 method. Also, we reveal the implementation of ToInt32. You can see that it checks for a null argument, and then calls int.Parse with the current culture. You could call int.Parse directly instead.
int.Parse for Integer ConversionProgram that invokes Convert.ToInt32 [C#]
using System;
class Program
{
static void Main()
{
string text = "500";
int num = Convert.ToInt32(text);
Console.WriteLine(num);
}
}
Output
500
Implementation of Convert.ToInt32 [C#]
public static int ToInt32(string value)
{
if (value == null)
{
return 0;
}
return int.Parse(value, CultureInfo.CurrentCulture);
}
There is really no benefit to using the Convert.ToInt32 method over the int.Parse method directly. In most cases, the int.TryParse method is probably best, as it doesn't slow performance down if an error occurs in the input. Instead of Convert.ToInt32, you could check for null on your own.
Cast Examples