Convert Strings to Integers - High-Flying C# Coding Tips


Sponsored Links

73058_New Scooba® 230 Floor Washing Robot + Free Shipping!

 

Convert Strings to Integers

Here we'll look at a way of converting Strings to Integers.

You may want to convert a string to an integer in many circumstances, for instance you want to take a user's value entered into a textbox and then use that as a number in some mathematical formula.

It is advisable to perform some kind of validation on the string first (or textbox contents) before attempting to convert a string into an integer as an exception may occur during the conversion.


In this example, we have an integer called '_number' with a value of '1234'. We then convert it into an integer using the Convert.ToInt32(string) method (provided that the string is actually a numeric value, called '_numberConversion'. After this we convert the integer back into a string called '_conversionBack' using the .ToString() method.



// take a string containing a number
string _number = "1234";

// convert the string into an integer
int _numberConversion = Convert.ToInt32(_number);

// here we convert the integer into a string, the string contains the number
string _conversionBack = _numberConversion.ToString();