One of the most common type conversions is from a string into an integer type. For example, if you need to perform mathematical operations on the resulting value or use it with a specific function.
In this tutorial, we will explore the Int32.Parse() method to convert a string type into an int using C#.
Using the Int32.Parse() Method
One of the most common and straightforward method of converting a string into an int in C# is the Int32.Parse() method.
As the name suggests, this method allows us to convert a string representation of a numerical value into its 32-bit signed integer version.
The function definition is as shown in the following:
The function accepts three main parameters:
- S – This denotes the string that contains the number that we wish to convert into an int.
- Style – This is a bitwise combination of enumeration values that is used to indicate the style of elements.
- IformatProvider – This specifies an object that supplies a culture-specific info about the format.
The function returns an int32 value upon the success of the provided string input.
The following shows a basic example that demonstrates how to use the Int32.Parse() method to convert a string into an int:
class Program
{
static void Main(string[] args)
{
string str = "100";
int i;
i = Int32.Parse(str);
Console.WriteLine(i);
}
}
In the given example, we use the Int32.Parse() method to convert the string “100” to its integer representation.
NOTE: Ensure that the provided string is a valid numerical value. Otherwise, the function will return a FormatException as follows:
class Program
{
static void Main(string[] args)
{
string str = "not a string";
int i;
i = Int32.Parse(str);
Console.WriteLine(i);
}
}
In this case, if we run the previous code, it should return an error since the input string is not a valid integer value.
Exception Handling
To avoid the program from crashing when it encounters a non-integer value, we can add a basic exception handling mechanism as follows:
class Program
{
static void Main(string[] args)
{
string str = "nan";
try
{
int i = Int32.Parse(str);
Console.WriteLine(i);
}
catch (FormatException e)
{
Console.WriteLine(e.Message);
}
}
}
In this case, when the function encounters an invalid input, it should print a message to the user denoting the input of an invalid value.
Conclusion
This tutorial explored how to work with the Int32.Parse() method in C# to convert a string value into an int.