Export (0) Print
Expand All

How to: Convert Data Types Using System.Convert 

The System.Convert class provides a complete set of methods for supported conversions. It provides a language-neutral way to perform conversions and is available to all languages that target the common language runtime. Whereas different languages might have different techniques for converting data types, the Convert class ensures that all common conversions are available in a generic format. This class performs narrowing conversions, as well as conversions to unrelated data types. For example, conversions from String types to numeric types, DateTime types to String types, and String types to Boolean types are supported. For a list of available conversions, see the list of methods in the Convert class. The Convert class performs checked conversions and always throws an exception if the conversion is not supported. The exception is often an OverflowException. For a list of supported conversions, see the type conversion tables.

You can pass the value that you want to convert to one of the appropriate methods in the Convert class and initialize the returned value to a new variable. For example, the following code uses the Convert class to transform a String value into a Boolean value.

Example

string MyString = "true";
bool MyBool = Convert.ToBoolean(MyString);
// MyBool has the value of True.

The Convert class is also useful if you have a string that you want to convert to a numeric value. The following code example converts a string that contains numeric characters into an Int32 value.

string newString = "123456789";
int MyInt = Convert.ToInt32(newString);
// MyInt has the value of 123456789.

The Convert class can also be used for a narrowing conversion that cannot be performed implicitly in the particular language you are using. The following code example shows a narrowing conversion from an Int64 to a smaller Int32 using the Convert.ToInt32 method.

Int64 MyInt64 = 123456789;
int MyInt = Convert.ToInt32(MyInt64);
// MyInt has the value of 123456789.

Sometimes performing a narrowing conversion with the Convert class changes the value of the item being converted. The following code example converts a Double into an Int32 value. In this case, the value is rounded from 42.72 to 43 in order to complete the conversion.

Double MyDouble = 42.72;
int MyInt = Convert.ToInt32(MyDouble);
// MyInt has the value of 43.

See Also

Community Additions

ADD
Show:
© 2014 Microsoft