C# String to Number Conversion
The eighteenth part of the C# Fundamentals tutorial brings together the native data types discussed so far. This article describes how to convert string values to numeric types. This is essential when allowing free-form user input of numeric data.
User input is often provided using unrestricted TextBoxes; the entered information becomes the contents of a string. If the textbox is being used to specify a number, the string may require conversion to a numeric data type.
In a previous article, we discussed implicit and explicit conversion between numeric types using the cast functions. Casting is unavailable when converting between strings and numeric values. Instead, the .NET framework provides a 'Convert' class specifically designed for converting between native types. The numeric types also provide methods for parsing strings.
Convert Class
The Convert class is found in the System namespace. It provides conversion functions as static methods. Static methods will be described in a later tutorial. For the purposes of the C# Fundamentals tutorial, it is enough to understand static methods are called without first creating an object. In other words, you do not need to create a Convert object to access the methods we require.
.NET Structures and C# Keywords
One complication when using the Convert class is that native C# data types are named differently than the underlying .NET framework structures. The following table lists the numeric and Boolean data types that have been described in the tutorial and the corresponding .NET names. The Convert class uses the case-sensitive .NET names.
Conversion Syntax
The static conversion methods follow a standardised syntax. The method name starts with 'To' followed by the desired .NET data type name. For example, to convert a string to a float, the method called is Convert.ToSingle. The string value to be converted is provided as a parameter.
// Convert a string to an integer<font></font>
int stringToInt = Convert.ToInt32("25");<font></font>
<font></font>
// Convert a string to a decimal<font></font>
decimal stringToDecimal = Convert.ToDecimal("25.5");<font></font>
<font></font>
// Booleans can be converted too<font></font>
bool stringToBoolean = Convert.ToBoolean("true");