An array of C#, PHP, and HTML programming articles, tutorials, and resources

Posts Tagged ‘ ToInt32 ’

Though very simple once you see the example, it may not be obvious right off the bat. Note that a simple cast from a string to int will not convert a string of integers to an int!

string stringVariable = "1234";
int integerVariable = (int)stringVariable;

Therefore, to accomplish converting from a string to int, following the sample code below:

string stringVariable = "1234";
int integerVariable = Convert.ToInt32(stringVariable);

The Convert class is part of the System namespace, which is included in nearly every project by default. If for any reason your string of integers contains invalid characters, the function ToInt32 will throw a FormatException.

Another, though less popular way is to convert a string of integers to an int variable is to use the function Parse in the Int32 class. An example is below:

string stringVariable = "1234";
int integerVariable = Int32.Parse(stringVariable);

The reason most programmers use the Convert class over the Int32 class is because the Convert class has the power to convert to and from a wide selection of variable types. In the end of the day, it really is a matter of preference, but I suggest first time programmers to get in the habit of using the Convert class.