System.Convert class
This article provides supplementary remarks to the reference documentation for this API.
The static Convert class contains methods that are primarily used to support conversion to and from the base data types in .NET. The supported base types are Boolean, Char, SByte, Byte, Int16, Int32, Int64, UInt16, UInt32, UInt64, Single, Double, Decimal, DateTime and String. In addition, the Convert class includes methods to support other kinds of conversions.
Conversions to and from base types
A conversion method exists to convert every base type to every other base type. However, the actual call to a particular conversion method can produce one of five outcomes, depending on the value of the base type at run time and the target base type. These five outcomes are:
No conversion. This occurs when an attempt is made to convert from a type to itself (for example, by calling Convert.ToInt32(Int32) with an argument of type Int32). In this case, the method simply returns an instance of the original type.
An InvalidCastException. This occurs when a particular conversion is not supported. An InvalidCastException is thrown for the following conversions:
A FormatException. This occurs when the attempt to convert a string value to any other base type fails because the string is not in the proper format. The exception is thrown for the following conversions:
- A string to be converted to a Boolean value does not equal Boolean.TrueString or Boolean.FalseString.
- A string to be converted to a Char value consists of multiple characters.
- A string to be converted to any numeric type is not recognized as a valid number.
- A string to be converted to a DateTime is not recognized as a valid date and time value.
A successful conversion. For conversions between two different base types not listed in the previous outcomes, all widening conversions as well as all narrowing conversions that do not result in a loss of data will succeed and the method will return a value of the targeted base type.
An OverflowException. This occurs when a narrowing conversion results in a loss of data. For example, trying to convert a Int32 instance whose value is 10000 to a Byte type throws an OverflowException because 10000 is outside the range of the Byte data type.
An exception will not be thrown if the conversion of a numeric type results in a loss of precision (that is, the loss of some least significant digits). However, an exception will be thrown if the result is larger than can be represented by the particular conversion method's return value type.
For example, when a Double is converted to a Single, a loss of precision might occur but no exception is thrown. However, if the magnitude of the Double is too large to be represented by a Single, an overflow exception is thrown.
Non-decimal numbers
The Convert class includes static methods that you can call to convert integral values to non-decimal string representations, and to convert strings that represent non-decimal numbers to integral values. Each of these conversion methods includes a base
argument that lets you specify the number system; binary (base 2), octal (base 8), and hexadecimal (base 16), as well as decimal (base 10). There is a set of methods to convert each of the CLS-compliant primitive integral types to a string, and one to convert a string to each of the primitive integral types:
ToString(Byte, Int32) and ToByte(String, Int32), to convert a byte value to and from a string in a specified base.
ToString(Int16, Int32) and ToInt16(String, Int32), to convert a 16-bit signed integer to and from a string in a specified base.
ToString(Int32, Int32) and ToInt32(String, Int32), to convert a 32-bit signed integer to and from a string in a specified base.
ToString(Int64, Int32) and ToInt64(String, Int32), to convert a 64-bit signed integer to and from a string in a specified base.
ToSByte(String, Int32), to convert the string representation of a byte value in a specified format to a signed byte.
ToUInt16(String, Int32), to convert the string representation of an integer in a specified format to an unsigned 16-bit integer.
ToUInt32(String, Int32), to convert the string representation of an integer in a specified format to an unsigned 32-bit integer.
ToUInt64(String, Int32), to convert the string representation of an integer in a specified format to an unsigned 64-bit integer.
The following example converts the value of Int16.MaxValue to a string in all supported numeric formats. It then converts the string value back to a Int16 value.
using System;
public class Example
{
public static void Main()
{
int[] baseValues = { 2, 8, 10, 16 };
short value = Int16.MaxValue;
foreach (var baseValue in baseValues) {
String s = Convert.ToString(value, baseValue);
short value2 = Convert.ToInt16(s, baseValue);
Console.WriteLine("{0} --> {1} (base {2}) --> {3}",
value, s, baseValue, value2);
}
}
}
// The example displays the following output:
// 32767 --> 111111111111111 (base 2) --> 32767
// 32767 --> 77777 (base 8) --> 32767
// 32767 --> 32767 (base 10) --> 32767
// 32767 --> 7fff (base 16) --> 32767
open System
let baseValues = [ 2; 8; 10; 16 ]
let value = Int16.MaxValue
for baseValue in baseValues do
let s = Convert.ToString(value, baseValue)
let value2 = Convert.ToInt16(s, baseValue)
printfn $"{value} --> {s} (base {baseValue}) --> {value2}"
// The example displays the following output:
// 32767 --> 111111111111111 (base 2) --> 32767
// 32767 --> 77777 (base 8) --> 32767
// 32767 --> 32767 (base 10) --> 32767
// 32767 --> 7fff (base 16) --> 32767
Module Example2
Public Sub Main()
Dim baseValues() As Integer = {2, 8, 10, 16}
Dim value As Short = Int16.MaxValue
For Each baseValue In baseValues
Dim s As String = Convert.ToString(value, baseValue)
Dim value2 As Short = Convert.ToInt16(s, baseValue)
Console.WriteLine("{0} --> {1} (base {2}) --> {3}",
value, s, baseValue, value2)
Next
End Sub
End Module
' The example displays the following output:
' 32767 --> 111111111111111 (base 2) --> 32767
' 32767 --> 77777 (base 8) --> 32767
' 32767 --> 32767 (base 10) --> 32767
' 32767 --> 7fff (base 16) --> 32767
Conversions from custom objects to base types
In addition to supporting conversions between the base types, the Convert method supports conversion of any custom type to any base type. To do this, the custom type must implement the IConvertible interface, which defines methods for converting the implementing type to each of the base types. Conversions that are not supported by a particular type should throw an InvalidCastException.
When the ChangeType method is passed a custom type as its first parameter, or when the Convert.To
Type method (such as Convert.ToInt32(Object) or Convert.ToDouble(Object, IFormatProvider) is called and passed an instance of a custom type as its first parameter, the Convert method, in turn, calls the custom type's IConvertible implementation to perform the conversion. For more information, see Type Conversion in .NET.
Culture-specific formatting information
All the base type conversion methods and the ChangeType method include overloads that have a parameter of type IFormatProvider. For example, the Convert.ToBoolean method has the following two overloads:
The IFormatProvider parameter can supply culture-specific formatting information to assist the conversion process. However, it is ignored by most of the base type conversion methods. It is used only by the following base type conversion methods. If a null
IFormatProvider argument is passed to these methods, the CultureInfo object that represents the current culture is used.
By methods that convert a value to a numeric type. The IFormatProvider parameter is used by the overload that has parameters of type String and IFormatProvider. It is also used by the overload that has parameters of type Object and IFormatProvider if the object's run-time type is a String.
By methods that convert a value to a date and time. The IFormatProvider parameter is used by the overload that has parameters of type String and IFormatProvider. It is also used by the overload that has parameters of type Object and IFormatProvider if the object's run-time type is a String.
By the Convert.ToString overloads that include an IFormatProvider parameter and that convert either a numeric value to a string or a DateTime value to a string.
However, any user-defined type that implements IConvertible can make use of the IFormatProvider parameter.
Base64 encoding
Base64 encoding converts binary data to a string. Data expressed as base-64 digits can be easily conveyed over data channels that can only transmit 7-bit characters. The Convert class includes the following methods to support base64 encoding: A set of methods support converting an array of bytes to and from a String or to and from an array of Unicode characters consisting of base-64 digit characters.
- ToBase64String, which converts a byte array to a base64-encoded string.
- ToBase64CharArray, which converts a byte array to a base64-encoded character array.
- FromBase64String, which converts a base64-encoded string to a byte array.
- FromBase64CharArray, which converts a base64-encoded character array to a byte array.
Other common conversions
You can use other .NET classes to perform some conversions that aren't supported by the static methods of the Convert class. These include:
Conversion to byte arrays
The BitConverter class provides methods that convert the primitive numeric types (including Boolean) to byte arrays and from byte arrays back to primitive data types.
Character encoding and decoding
The Encoding class and its derived classes (such as UnicodeEncoding and UTF8Encoding) provide methods to encode a character array or a string (that is, to convert them to a byte array in a particular encoding) and to decode an encoded byte array (that is, convert a byte array back to UTF16-encoded Unicode characters). For more information, see Character Encoding in .NET.
Examples
The following example demonstrates some of the conversion methods in the Convert class, including ToInt32, ToBoolean, and ToString.
double dNumber = 23.15;
try {
// Returns 23
int iNumber = System.Convert.ToInt32(dNumber);
}
catch (System.OverflowException) {
System.Console.WriteLine(
"Overflow in double to int conversion.");
}
// Returns True
bool bNumber = System.Convert.ToBoolean(dNumber);
// Returns "23.15"
string strNumber = System.Convert.ToString(dNumber);
try {
// Returns '2'
char chrNumber = System.Convert.ToChar(strNumber[0]);
}
catch (System.ArgumentNullException) {
System.Console.WriteLine("String is null");
}
catch (System.FormatException) {
System.Console.WriteLine("String length is greater than 1.");
}
// System.Console.ReadLine() returns a string and it
// must be converted.
int newInteger = 0;
try {
System.Console.WriteLine("Enter an integer:");
newInteger = System.Convert.ToInt32(
System.Console.ReadLine());
}
catch (System.ArgumentNullException) {
System.Console.WriteLine("String is null.");
}
catch (System.FormatException) {
System.Console.WriteLine("String does not consist of an " +
"optional sign followed by a series of digits.");
}
catch (System.OverflowException) {
System.Console.WriteLine(
"Overflow in string to int conversion.");
}
System.Console.WriteLine("Your integer as a double is {0}",
System.Convert.ToDouble(newInteger));
let dNumber = 23.15
try
// Returns 23
Convert.ToInt32 dNumber
|> ignore
with :? OverflowException ->
printfn "Overflow in double to int conversion."
// Returns True
let bNumber = System.Convert.ToBoolean dNumber
// Returns "23.15"
let strNumber = System.Convert.ToString dNumber
try
// Returns '2'
System.Convert.ToChar strNumber[0]
|> ignore
with
| :? ArgumentNullException ->
printfn "String is null"
| :? FormatException ->
printfn "String length is greater than 1."
// System.Console.ReadLine() returns a string and it
// must be converted.
let newInteger =
try
printfn "Enter an integer:"
System.Convert.ToInt32(Console.ReadLine())
with
| :? ArgumentNullException ->
printfn "String is null."
0
| :? FormatException ->
printfn "String does not consist of an optional sign followed by a series of digits."
0
| :? OverflowException ->
printfn "Overflow in string to int conversion."
0
printfn $"Your integer as a double is {System.Convert.ToDouble newInteger}"
Dim dNumber As Double
dNumber = 23.15
Try
' Returns 23
Dim iNumber As Integer
iNumber = System.Convert.ToInt32(dNumber)
Catch exp As System.OverflowException
System.Console.WriteLine("Overflow in double to int conversion.")
End Try
' Returns True
Dim bNumber As Boolean
bNumber = System.Convert.ToBoolean(dNumber)
' Returns "23.15"
Dim strNumber As String
strNumber = System.Convert.ToString(dNumber)
Try
' Returns '2'
Dim chrNumber As Char
chrNumber = System.Convert.ToChar(strNumber.Chars(1))
Catch exp As System.ArgumentNullException
System.Console.WriteLine("String is null.")
Catch exp As System.FormatException
System.Console.WriteLine("String length is greater than 1.")
End Try
' System.Console.ReadLine() returns a string and it
' must be converted.
Dim newInteger As Integer
newInteger = 0
Try
System.Console.WriteLine("Enter an integer:")
newInteger = System.Convert.ToInt32(System.Console.ReadLine())
Catch exp As System.ArgumentNullException
System.Console.WriteLine("String is null.")
Catch exp As System.FormatException
System.Console.WriteLine("String does not consist of an " + _
"optional sign followed by a series of digits.")
Catch exp As System.OverflowException
System.Console.WriteLine("Overflow in string to int conversion.")
End Try
System.Console.WriteLine("Your integer as a double is {0}", _
System.Convert.ToDouble(newInteger))