Export (0) Print
Expand All
4 out of 17 rated this helpful - Rate this topic

Convert Class

Converts a base data type to another base data type.

Namespace: System
Assembly: mscorlib (in mscorlib.dll)

public static class Convert
public final class Convert
public final class Convert
Not applicable.

This class returns a type whose value is equivalent to the value of a specified type. The supported base types are Boolean, Char, SByte, Byte, Int16, Int32, Int64, UInt16, UInt32, UInt64, Single, Double, Decimal, DateTime and String.

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 four outcomes, depending on the value of the base type at run time and the target base type. These four 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:

    • Conversions from Char to Boolean, Single, Double, Decimal, or DateTime.

    • Conversions from Boolean, Single, Double, Decimal, or DateTime to Char.

    • Conversions from DateTime to any other type except String.

    • Conversions from any other type, except String, to DateTime.

  • 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.

A set of methods support converting an array of bytes to and from a String or array of Unicode characters consisting of base 64 digit characters. Data expressed as base 64 digits can be easily conveyed over data channels that can only transmit 7-bit characters.

Some of the methods in this class take a parameter object that implements the IFormatProvider interface. This parameter can supply culture-specific formatting information to assist the conversion process. The base value types ignore this parameter, but any user-defined type that implements IConvertible can honor it.

For more information about the base value types, see the appropriate topic listed in the See Also section.

The following code 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));

double dNumber = 23.15;

try {        
    // Returns 23
    int iNumber = System.Convert.ToInt32(dNumber);
}
catch (System.OverflowException exp) {        
    System.Console.WriteLine("Overflow in double to int conversion.");
}

// Returns True
boolean bNumber = System.Convert.ToBoolean(dNumber);

// Returns "23.15"
String strNumber = System.Convert.ToString(dNumber);

try {        
    // Returns '2'
    char chrNumber = System.Convert.ToChar(strNumber.get_Chars(0));
}
catch (System.ArgumentNullException exp) {        
    System.Console.WriteLine("String is null");
}
catch (System.FormatException exp) {        
    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 exp) {        
    System.Console.WriteLine("String is null.");
}
catch (System.FormatException exp) {        
    System.Console.WriteLine(("String does not consist of an " 
        + "optional sign followed by a series of digits."));
}
catch (System.OverflowException exp) {        
    System.Console.WriteLine("Overflow in string to int conversion.");
}
System.Console.WriteLine("Your integer as a double is {0}", 
    System.Convert.ToString(System.Convert.ToDouble(newInteger)));

The following code example demonstrates several of the conversion methods in the Convert class.

// Sample for the Convert class summary.
using System;

class Sample 
{
    public static void Main() 
    {
    string nl = Environment.NewLine;
    string str = "{0}Return the Int64 equivalent of the following base types:{0}";
    bool    xBool = false;
    short   xShort = 1;
    int     xInt   = 2;
    long    xLong  = 3;
    float   xSingle = 4.0f;
    double  xDouble = 5.0;
    decimal xDecimal = 6.0m;
    string  xString = "7";
    char    xChar   = '8'; // '8' = hexadecimal 38 = decimal 56
    byte    xByte  =  9;

//  The following types are not CLS-compliant.
    ushort  xUshort = 120;   
    uint    xUint =   121;
    ulong   xUlong =  122;
    sbyte   xSbyte  = 123;

//  The following type cannot be converted to an Int64.
//  DateTime xDateTime = DateTime.Now;

    Console.WriteLine(str, nl);
    Console.WriteLine("Boolean:  {0}", Convert.ToInt64(xBool));
    Console.WriteLine("Int16:    {0}", Convert.ToInt64(xShort));
    Console.WriteLine("Int32:    {0}", Convert.ToInt64(xInt));
    Console.WriteLine("Int64:    {0}", Convert.ToInt64(xLong));
    Console.WriteLine("Single:   {0}", Convert.ToInt64(xSingle));
    Console.WriteLine("Double:   {0}", Convert.ToInt64(xDouble));
    Console.WriteLine("Decimal:  {0}", Convert.ToInt64(xDecimal));
    Console.WriteLine("String:   {0}", Convert.ToInt64(xString));
    Console.WriteLine("Char:     {0}", Convert.ToInt64(xChar));
    Console.WriteLine("Byte:     {0}", Convert.ToInt64(xByte));
    Console.WriteLine("DateTime: There is no example of this conversion because");
    Console.WriteLine("          a DateTime cannot be converted to an Int64.");
//
    Console.WriteLine("{0}The following types are not CLS-compliant.{0}", nl);
    Console.WriteLine("UInt16:   {0}", Convert.ToInt64(xUshort));
    Console.WriteLine("UInt32:   {0}", Convert.ToInt64(xUint));
    Console.WriteLine("UInt64:   {0}", Convert.ToInt64(xUlong));
    Console.WriteLine("SByte:    {0}", Convert.ToInt64(xSbyte));
    }
}
/*
This example produces the following results:

Return the Int64 equivalent of the following base types:

Boolean:  0
Int16:    1
Int32:    2
Int64:    3
Single:   4
Double:   5
Decimal:  6
String:   7
Char:     56
Byte:     9
DateTime: There is no example of this conversion because
          a DateTime cannot be converted to an Int64.

The following types are not CLS-compliant.

UInt16:   120
UInt32:   121
UInt64:   122
SByte:    123
*/

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 98, Windows Server 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0, 1.0

XNA Framework

Supported in: 1.0
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.