top

Search

C# Tutorial

Type conversion or type casting involves converting one data type to another. There are mainly two types of type conversion in C#. These are given as follows:Implicit Type ConversionImplicit type conversion is performed by the compiler implicitly in a way that is type-safe. These types of conversions can include char to int, int to float etc. Conversions from derived classes to base classes are also a part of implicit type conversion.A program that demonstrates implicit type conversion is given as follows:Source Code: Program that demonstrates implicit type conversion in C#using System;   namespace ImplicitConversionDemo   {      class Example    {        static void Main(string[] args)          {            int a = 5;            int b = 3;            float c;            c = a * b;            Console.WriteLine("Product of {0} and {1} is {2}", a, b, c);          }    } }The output of the above program is as follows:Product of 5 and 3 is 15Now let us understand the above program.In the program, a and b are int variables that contain the values 5 and 3 respectively. They are multiplied and the resultant value in stored in c which is of type double. This shows implicit type conversion. Then the values of a, b and c are displayed. The code snippet for this is as follows:int a = 5;  int b = 3;double c;c = a * b;Console.WriteLine("Product of {0} and {1} is {2}", a, b, c);Explicit Type ConversionExplicit type conversion is performed by the compiler explicitly by requesting the conversion of a data type into another data type. This requires a cast operator as the compiler is forced to make the transformation.Cast operators are unsafe and can lead to the loss of data if a larger data type is converted into a smaller data type.A program that demonstrates explicit type conversion is given as follows:Source Code: Program that demonstrates explicit type conversion in C#using System;   namespace ExplicitConversionDemo   {      class Example    {        static void Main(string[] args)          {            double a = 7.5;              double b = 3.5;            double c;            int d;            c = a * b;            d = (int)c;            Console.WriteLine("Product of {0} and {1} is {2}", a, b, c);              Console.WriteLine("Value after Explicit Type Conversion is {0}", d);          }    } }The output of the above program is as follows:Product of 7.5 and 3.5 is 26.25 Value after Explicit Type Conversion is 26Now let us understand the above program.In the program, a and b are double variables that contain the values 7.5 and 3.5 respectively. They are multiplied and the resultant value in stored in c which is also of type double. Then the value of c is stored in d using explicit type casting as d is of type int.Then the values of a, b and c are displayed. Also, the value stored in d after explicit type casting is also displayed. The code snippet for this is as follows: double a = 7.5;              double b = 3.5;            double c;            int d;            c = a * b;            d = (int)c;            Console.WriteLine("Product of {0} and {1} is {2}", a, b, c);              Console.WriteLine("Value after Explicit Type Conversion is {0}", d);Let us now see some examples of Type Conversions and Conversions in C# using the Convert class:Convert Integer to StringIf you want to convert Integer to String in C#, then use the ToString() method that represents any value as a string.Let us now see an example:Source Code: Program that converts Integer to String in C#using System; class Example {  static void Main(string[] args)  {         String str;    int val = 130;    str = val.ToString();    Console.WriteLine("String = "+str);    Console.ReadLine();  } }The above program generates the following output:String = 130Convert Binary to DecimalTo convert binary value to decimal, let us see the code. Our binary value here is 11100:Source Code: Program that converts binary value to decimal in C#using System; using System.Collections.Generic; using System.Text; namespace BinDecExample {    class Example    {        static void Main(string[] args)        {            int n, rem, bin;            int dec = 0, baseValue = 1;            n = 11100;            Console.Write("\nBinary: "+n);            bin = n;            while (n > 0)            {                rem = n % 10;                dec = dec + rem * baseValue;                n = n / 10 ;                baseValue = baseValue * 2;            }            Console.Write("\nConverted to Decimal: "+dec);            Console.ReadLine();        }    } }The above program generates the following output:Binary: 11100 Converted to Decimal: 28Convert Decimal to OctalTo convert Decimal value to Octal, let us see the following code:Source Code: Program that converts Decimal value to Octal in C#using System; namespace DecOctExample {   class Example {      static void Main(string[] args) {        int i = 0;        int []val = new int[30];        int dec = 30;        Console.WriteLine("Decimal...\n"+dec);        while (dec != 0)        {            val[i] = dec % 8;            dec = dec / 8;            i++;        }        Console.WriteLine("Octal...");        for (int k = i - 1; k >= 0; k--)            Console.Write(val[k]);         Console.ReadKey();      }   } }The above program generates the following output:Decimal... 30 Octal... 36Convert Float to BinaryTo convert float to binary, the following code is displayed below:Source Code: Program that converts float to binary in C#using System; using System.IO; using System.CodeDom.Compiler; namespace FloatBinExample { class Example {  static void Main(string[] args) {   float f = 22.3f;   Console.WriteLine("Float = "+f);   string str = "";   while (f >= 1) {    str = (f % 2) + str;    f = f / 2;   }   Console.Write(str);  } } }The above program generates the following output:Float = 22.3 1.393750.78749991.5751.150.2999992Convert string to intTo convert string to int, the Int32.Parse() method is used. Let us see how the method is used for conversion:Source Code: Program that converts string to int in C#using System; class Example { static void Main() {  string str ="877";  int res = Int32.Parse(str);  Console.WriteLine("int = "+res); } }The above program generates the following output:int = 877Convert Hex String to Hex NumberThe Convert.ToSByte() method is used to convert hex string to hex number. Do not forget to set the radix as 16, since Hexadecimal is represented by 16 radix.Let us see an example now:Source Code: Program that converts hex string to hex number in C#using System; namespace Example {   public class Demo {      public static void Main(string[] args) {        string hexStr = "3E";          Console.WriteLine("Hex String = "+hexStr);        Console.WriteLine("Hex = "+Convert.ToSByte(hexStr, 16));      }   } }The above program generates the following output:Hex String = 3E Hex = 62Convert string to boolThe Bool.parse() method is used in C# to convert string to bool. Let us see an example:Source Code: Program that converts string to bool in C#using System; using System.Linq; class Example {    static void Main()    {        string myStr = "true";        bool b = bool.Parse(myStr);        Console.WriteLine(b);    } }The above program generates the following output:TrueConvert string to longThe Long.parse() method is to be used in C# to convert string to long.Let us see an example:Source Code: Program that converts string to long in C#using System; using System.Linq; class Example {    static void Main()    {        string s = "7887687687";        long res = long.Parse(s);        Console.WriteLine(res);    } }The above program generates the following output:7887687687Convert Int32 value to a DecimalThe Convert.ToDecimal() method is used in C# to converts 32-bit signed integer to decimal in C#:Source Code: Program that converts 32-bit signed integer to decimal in C#using System; public class Demo {    public static void Main() {        int i = 866;        Console.WriteLine(" Int32 = "+ i);        decimal res = Convert.ToDecimal(i);        Console.WriteLine(" Converted to decimal = "+ res);    } }The above program generates the following output:Int32 = 866 Converted to decimal = 866Convert  Byte value to Int32 valueThe Convert.ToInt32() method is used in C# to convert Byte value to Int32 value. Let us see an example:Source Code: Program that converts Byte value to Int32 value in C#using System; public class Example {    public static void Main() {        byte b = 100;        int res = Convert.ToInt32(b);          Console.WriteLine("Converted byte to Int32  = "+res);    } }The above program generates the following output:Converted byte to Int32  = 100Convert Double value to Int64 valueThe Convert.ToInt64() method is used to convert a Double value to Int64 value:Source Code: Program that converts Double value to Int64 value in C#using System; public class Example {    public static void Main() {        double d = 35.873628e12;        long res = Convert.ToInt64(d);          Console.WriteLine("Converted = {0:E} to {1:N0} ", d, res);    } }The above program generates the following output:Converted = 3.587363E+013 to 35,873,628,000,000Convert Double to an Integer ValueThe Convert.ToInt32() method is used in C# to convert Double to an Integer value:Source Code: Program that converts Double to an Integer in C#using System; public class Example {    public static void Main() {        double d = 34.23;        int i = Convert.ToInt32(d);          Console.WriteLine("Converted {0} to {1} ", d, i);    } }The above program generates the following output:Converted 34.23 to 34Convert class in C#The Convert class in C# converts one datatype to another. Let us see some example of the conversion methods:Convert.ToInt16() MethodThe Convert.ToInt16() method is used to convert a value to a 16-bit signed integer.Let us see an example:Source Code: Program that demonstrates Convert.ToInt16() in C#using System; public class Example {    public static void Main() {      double d = 1.955;      short s;      Console.WriteLine("Converting...");      s = Convert.ToInt16(d);      Console.WriteLine("Converted {0} to {1}", d, s);    } }The above program generates the following output:Converting... Converted 1.955 to 2Convert.ToUInt16() MethodThe Convert.ToUInt16() method is used to convert a value to a 16-bit unsigned integer.Let us see an example:Source Code: Program that demonstrates Convert.ToUInt16() in C#using System; public class Example {    public static void Main() {        string s = "19";        ushort us;        Console.WriteLine("Converting...");        // converting        us = Convert.ToUInt16(s);        Console.WriteLine("Converted string '{0}' to {1}", s, us);    } }The above program generates the following output:Converting... Converted string '19' to 19Convert.ToDecimal() MethodThe Convert.ToDecimal() method is used to convert a value to a decimal number. Let us see an example:Source Code: Program that demonstrates Convert.ToDecimal() in C#using System; public class Example {    public static void Main() {      decimal dec;      string str = "7,294.56";      System.Console.WriteLine("String = "+str);      dec = System.Convert.ToDecimal(str);  System.Console.WriteLine("Converted to decimal = {0} ", dec);    } }The above program generates the following output:String = 7,294.56 Converted to decimal = 7294.56Convert.ToInt64() MethodThe Convert.ToInt64() method is to be used for converting Decimal to Int64 in C#. Let us see an example:Source Code: Program that demonstrates Convert.ToInt64()  in C#using System; class Example {    static void Main()    {        decimal d = 245.54m;        long res;        Console.WriteLine("Decimal = "+d);        res = Convert.ToInt64(d);        Console.WriteLine("Int64 = "+ res);    } }The above program generates the following output:Decimal = 245.54 Int64 = 246Convert.ToSingle() MethodThe ToSingle() method is used to convert a value to a single-precision floating-point:Let us see an example:Source Code: Program that demonstrates Convert.ToSingle() in C#using System; public class Example {    public static void Main() {        bool b = true;        float f;        Console.WriteLine("Bool: "+b);        f = Convert.ToSingle(b);        Console.WriteLine("Converted: {0} to {1}", b, f);    } }The above program generates the following output:Bool: True Converted: True to 1Convert.ToChar() MethodConvert a specified value to a Unicode integer using ToChar() method. Let us see an example:Source Code: Program that demonstrates Convert.ToChar() in C#The using System; public class Demo {    public static void Main() {        sbyte[] myByte = { 34, 45, 87, 101, 102, 103 };        char ch;        foreach (sbyte sb in myByte)        {           ch = Convert.ToChar(sb);           Console.WriteLine("{0} converted to '{1}'", sb, ch);        }    } }The above program generates the following output:34 converted to '"' 45 converted to '-' 87 converted to 'W' 101 converted to 'e' 102 converted to 'f' 103 converted to 'g'Convert.ToDateTime() MethodTo convert a given value to DateTime value, use the Convert.ToDateTime method.Let us see an example:Source Code: Program that demonstrates Convert.ToDateTime() in C#using System; public class Example {    public static void Main() {      string str;      DateTime dt;      str = "11/11/2018";      Console.WriteLine("String = "+str);      dt = Convert.ToDateTime(str);      Console.WriteLine("Converted to  = "+dt);    } }The above program generates the following output:String = 11/11/2018 Converted to  = 11/11/2018 12:00:00 AMConvert.ToInt32() MethodThe Convert.ToInt32() method is to be used in C# to convert a value to a 32-bit signed integer.Let us see an example:Source Code: Program that demonstrates Convert.ToInt32() in C#using System; public class Demo {    public static void Main() {      double d = 25.68;      Console.WriteLine("Double value = "+d);      int i;      i = Convert.ToInt32(d);      Console.WriteLine("Converted {0} to {1}", d, i);    } }The above program generates the following output:Double value = 25.68 Converted 25.68 to 26Convert.ToInt64() MethodThe Convert.ToInt64() method is to be used in C# to convert a value to a 64-bit signed integer.Let us see an example:Source Code: Program that demonstrates Convert.ToInt64() in C#using System; public class Demo {    public static void Main() {      double d = 588.654;      Console.WriteLine("Double: "+d);      long l;      l = Convert.ToInt32(d);      Console.WriteLine("Converted to long = "+l);    } }The above program generates the following output:Double: 588.654 Converted to long = 589Convert.ToSByte() MethodThe Convert.ToSByte() method is used to convert a value to SByte. The SByte type is an 8-bit signed integer.Let us see an example:Source Code: Program that demonstrates Convert.ToSByte() in C#using System; public class Example {    public static void Main() {      double d = 30.6;      Console.WriteLine("Double = "+d);      sbyte sb;      sb = Convert.ToSByte(d);      Console.WriteLine("Converted to SByte = "+sb);    } }The above program generates the following output:Double = 30.6 Converted to SByte = 31Convert.ToDouble() MethodThe Convert.ToDouble() method is used to convert a value to a double-precision floating-point number.Source Code: Program that demonstrates Convert.ToDouble() in C#using System; public class Demo {    public static void Main() {      long[] val = { 87687, 154416546, -8768767};      double d;       foreach (long a in val)        {             Console.WriteLine(a);        }        Console.WriteLine("Converted to...");       foreach (long a in val)        {           d = Convert.ToDouble(a);           Console.WriteLine(d);        }    } }The above program generates the following output:87687 154416546 -8768767 Converted to... 87687 154416546 -8768767Convert.ToString() MethodThe ToString() method is used in C# to convert the value to its equivalent stringLet us see an example:Source Code: Program that demonstrates Convert.ToString() in C#using System; public class Demo {    public static void Main() {        bool b = true;        Console.WriteLine(b);        Console.WriteLine(Convert.ToString(b));         } }The above program generates the following output:True TrueConvert.ToBoolean() MethodTo convert a specified value to an equivalent Boolean value, use the Convert.ToBoolean() method.Let us see an example:Source Code: Program that demonstrates Convert.ToBoolean() in C#using System; public class Example {    public static void Main() {        double d = 89.767;        bool b;        Console.WriteLine("Double: "+d);        b = System.Convert.ToBoolean(d);        Console.WriteLine("Converted to Boolean equivalent: "+b);    } }The above program generates the following output:Double: 89.767 Converted to Boolean equivalent: TrueConvert.ToByte() MethodConvert a specified value to an 8-bit unsigned integer using the Convert.ToByte() method.Let us see an example:Source Code: Program that demonstrates Convert.ToByte() in C#using System; public class Example {    public static void Main() {        char[] ch = { 'a', 'b'};        Console.WriteLine("Values...");        foreach (char c in ch)        {          Console.WriteLine(c);        }        Console.WriteLine("Conversion...");        foreach (char c in ch)        {           byte b = Convert.ToByte(c);           Console.WriteLine("{0} Converted to Byte = {1} ",c, b);        }    } }The above program generates the following output:Values... a b Conversion... a Converted to Byte = 97 b Converted to Byte = 98Convert.ToUInt64() MethodConvert a value to a 64-bit unsigned integer using the Convert.ToUInt64() method.Let us see an example:Source Code: Program that demonstrates Convert.ToUInt64() in C#using System; public class Example {    public static void Main() {        char c = 'y';        ulong ul;        Console.WriteLine("Char: "+c);        ul = Convert.ToUInt64(c);        Console.WriteLine("After conversion: "+ul);    } }The above program generates the following output:Char: y After conversion: 121Convert.ToUInt32() MethodThe Convert.ToUInt32() method is used to convert a specified value to a 32-bit unsigned integer.Let us see an example:Source Code: Program that demonstrates Convert.ToUInt32() in C#using System; public class Example {    public static void Main() {        string s = "30";        uint ui;        ui = Convert.ToUInt32(s);        Console.WriteLine("Converted value: "+ui);    } }The following is the output:Converted value: 30
logo

C# Tutorial

Type Conversion in C#

Type conversion or type casting involves converting one data type to another. There are mainly two types of type conversion in C#. These are given as follows:

Implicit Type Conversion

Implicit type conversion is performed by the compiler implicitly in a way that is type-safe. These types of conversions can include char to int, int to float etc. Conversions from derived classes to base classes are also a part of implicit type conversion.

A program that demonstrates implicit type conversion is given as follows:

Source Code: Program that demonstrates implicit type conversion in C#

using System;  
namespace ImplicitConversionDemo  
{  
   class Example
   {
       static void Main(string[] args)  
       {
           int a = 5;
           int b = 3;
           float c;
           c = a * b;
           Console.WriteLine("Product of {0} and {1} is {2}", a, b, c);  
       }
   }
}

The output of the above program is as follows:

Product of 5 and 3 is 15

Now let us understand the above program.

In the program, a and b are int variables that contain the values 5 and 3 respectively. They are multiplied and the resultant value in stored in c which is of type double. This shows implicit type conversion. Then the values of a, b and c are displayed. The code snippet for this is as follows:

int a = 5;  
int b = 3;

double c;
c = a * b;

Console.WriteLine("Product of {0} and {1} is {2}", a, b, c);

Explicit Type Conversion

Explicit type conversion is performed by the compiler explicitly by requesting the conversion of a data type into another data type. This requires a cast operator as the compiler is forced to make the transformation.

Cast operators are unsafe and can lead to the loss of data if a larger data type is converted into a smaller data type.

A program that demonstrates explicit type conversion is given as follows:

Source Code: Program that demonstrates explicit type conversion in C#

using System;  
namespace ExplicitConversionDemo  
{  
   class Example
   {
       static void Main(string[] args)  
       {
           double a = 7.5;  
           double b = 3.5;
           double c;
           int d;
           c = a * b;
           d = (int)c;
           Console.WriteLine("Product of {0} and {1} is {2}", a, b, c);  
           Console.WriteLine("Value after Explicit Type Conversion is {0}", d);  
       }
   }
}

The output of the above program is as follows:

Product of 7.5 and 3.5 is 26.25
Value after Explicit Type Conversion is 26

Now let us understand the above program.

In the program, a and b are double variables that contain the values 7.5 and 3.5 respectively. They are multiplied and the resultant value in stored in c which is also of type double. Then the value of c is stored in d using explicit type casting as d is of type int.

Then the values of a, b and c are displayed. Also, the value stored in d after explicit type casting is also displayed. The code snippet for this is as follows:

 double a = 7.5;  
           double b = 3.5;
           double c;
           int d;
           c = a * b;
           d = (int)c;
           Console.WriteLine("Product of {0} and {1} is {2}", a, b, c);  
           Console.WriteLine("Value after Explicit Type Conversion is {0}", d);

Let us now see some examples of Type Conversions and Conversions in C# using the Convert class:

Convert Integer to String

If you want to convert Integer to String in C#, then use the ToString() method that represents any value as a string.

Let us now see an example:

Source Code: Program that converts Integer to String in C#

using System;
class Example {
 static void Main(string[] args)
 {     
   String str;
   int val = 130;
   str = val.ToString();
   Console.WriteLine("String = "+str);
   Console.ReadLine();
 }
}

The above program generates the following output:

String = 130

Convert Binary to Decimal

To convert binary value to decimal, let us see the code. Our binary value here is 11100:

Source Code: Program that converts binary value to decimal in C#

using System;
using System.Collections.Generic;
using System.Text;
namespace BinDecExample
{
   class Example
   {
       static void Main(string[] args)
       {
           int n, rem, bin;
           int dec = 0, baseValue = 1;
           n = 11100;
           Console.Write("\nBinary: "+n);
           bin = n;
           while (n > 0)
           {
               rem = n % 10;
               dec = dec + rem * baseValue;
               n = n / 10 ;
               baseValue = baseValue * 2;
           }
           Console.Write("\nConverted to Decimal: "+dec);
           Console.ReadLine();
       }
   }
}

The above program generates the following output:

Binary: 11100
Converted to Decimal: 28

Convert Decimal to Octal

To convert Decimal value to Octal, let us see the following code:

Source Code: Program that converts Decimal value to Octal in C#

using System;
namespace DecOctExample {
  class Example {
     static void Main(string[] args) {
       int i = 0;
       int []val = new int[30];
       int dec = 30;
       Console.WriteLine("Decimal...\n"+dec);
       while (dec != 0)
       {
           val[i] = dec % 8;
           dec = dec / 8;
           i++;
       }
       Console.WriteLine("Octal...");
       for (int k = i - 1; k >= 0; k--)
           Console.Write(val[k]);
        Console.ReadKey();
     }
  }
}

The above program generates the following output:

Decimal...
30
Octal...
36

Convert Float to Binary

To convert float to binary, the following code is displayed below:

Source Code: Program that converts float to binary in C#

using System;
using System.IO;
using System.CodeDom.Compiler;
namespace FloatBinExample {
class Example {
 static void Main(string[] args) {
  float f = 22.3f;
  Console.WriteLine("Float = "+f);
  string str = "";
  while (f >= 1) {
   str = (f % 2) + str;
   f = f / 2;
  }
  Console.Write(str);
 }
}
}

The above program generates the following output:

Float = 22.3
1.393750.78749991.5751.150.2999992

Convert string to int

To convert string to int, the Int32.Parse() method is used. Let us see how the method is used for conversion:

Source Code: Program that converts string to int in C#

using System;
class Example {
static void Main() {
 string str ="877";
 int res = Int32.Parse(str);
 Console.WriteLine("int = "+res);
}
}

The above program generates the following output:

int = 877

Convert Hex String to Hex Number

The Convert.ToSByte() method is used to convert hex string to hex number. Do not forget to set the radix as 16, since Hexadecimal is represented by 16 radix.

Let us see an example now:

Source Code: Program that converts hex string to hex number in C#

using System;
namespace Example {
  public class Demo {
     public static void Main(string[] args) {
       string hexStr = "3E";  
       Console.WriteLine("Hex String = "+hexStr);
       Console.WriteLine("Hex = "+Convert.ToSByte(hexStr, 16));
     }
  }
}

The above program generates the following output:

Hex String = 3E
Hex = 62

Convert string to bool

The Bool.parse() method is used in C# to convert string to bool. Let us see an example:

Source Code: Program that converts string to bool in C#

using System;
using System.Linq;
class Example
{
   static void Main()
   {
       string myStr = "true";
       bool b = bool.Parse(myStr);
       Console.WriteLine(b);
   }
}

The above program generates the following output:

True

Convert string to long

The Long.parse() method is to be used in C# to convert string to long.

Let us see an example:

Source Code: Program that converts string to long in C#

using System;
using System.Linq;
class Example
{
   static void Main()
   {
       string s = "7887687687";
       long res = long.Parse(s);
       Console.WriteLine(res);
   }
}

The above program generates the following output:

7887687687

Convert Int32 value to a Decimal

The Convert.ToDecimal() method is used in C# to converts 32-bit signed integer to decimal in C#:

Source Code: Program that converts 32-bit signed integer to decimal in C#

using System;
public class Demo {
   public static void Main() {
       int i = 866;
       Console.WriteLine(" Int32 = "+ i);
       decimal res = Convert.ToDecimal(i);
       Console.WriteLine(" Converted to decimal = "+ res);
   }
}

The above program generates the following output:

Int32 = 866
Converted to decimal = 866

Convert  Byte value to Int32 value

The Convert.ToInt32() method is used in C# to convert Byte value to Int32 value. Let us see an example:

Source Code: Program that converts Byte value to Int32 value in C#

using System;
public class Example {
   public static void Main() {
       byte b = 100;
       int res = Convert.ToInt32(b);  
       Console.WriteLine("Converted byte to Int32  = "+res);
   }
}

The above program generates the following output:

Converted byte to Int32  = 100

Convert Double value to Int64 value

The Convert.ToInt64() method is used to convert a Double value to Int64 value:

Source Code: Program that converts Double value to Int64 value in C#

using System;
public class Example {
   public static void Main() {
       double d = 35.873628e12;
       long res = Convert.ToInt64(d);  
       Console.WriteLine("Converted = {0:E} to {1:N0} ", d, res);
   }
}

The above program generates the following output:

Converted = 3.587363E+013 to 35,873,628,000,000

Convert Double to an Integer Value

The Convert.ToInt32() method is used in C# to convert Double to an Integer value:

Source Code: Program that converts Double to an Integer in C#

using System;
public class Example {
   public static void Main() {
       double d = 34.23;
       int i = Convert.ToInt32(d);  
       Console.WriteLine("Converted {0} to {1} ", d, i);
   }
}

The above program generates the following output:

Converted 34.23 to 34

Convert class in C#

The Convert class in C# converts one datatype to another. Let us see some example of the conversion methods:

Convert.ToInt16() Method

The Convert.ToInt16() method is used to convert a value to a 16-bit signed integer.

Let us see an example:

Source Code: Program that demonstrates Convert.ToInt16() in C#

using System;
public class Example {
   public static void Main() {
     double d = 1.955;
     short s;
     Console.WriteLine("Converting...");
     s = Convert.ToInt16(d);
     Console.WriteLine("Converted {0} to {1}", d, s);
   }
}

The above program generates the following output:

Converting...
Converted 1.955 to 2

Convert.ToUInt16() Method

The Convert.ToUInt16() method is used to convert a value to a 16-bit unsigned integer.

Let us see an example:

Source Code: Program that demonstrates Convert.ToUInt16() in C#

using System;
public class Example {
   public static void Main() {
       string s = "19";
       ushort us;
       Console.WriteLine("Converting...");
       // converting
       us = Convert.ToUInt16(s);
       Console.WriteLine("Converted string '{0}' to {1}", s, us);
   }
}

The above program generates the following output:

Converting...
Converted string '19' to 19

Convert.ToDecimal() Method

The Convert.ToDecimal() method is used to convert a value to a decimal number. Let us see an example:

Source Code: Program that demonstrates Convert.ToDecimal() in C#

using System;
public class Example {
   public static void Main() {
     decimal dec;
     string str = "7,294.56";
     System.Console.WriteLine("String = "+str);
     dec = System.Convert.ToDecimal(str);
 System.Console.WriteLine("Converted to decimal = {0} ", dec);
   }
}

The above program generates the following output:

String = 7,294.56
Converted to decimal = 7294.56

Convert.ToInt64() Method

The Convert.ToInt64() method is to be used for converting Decimal to Int64 in C#. Let us see an example:

Source Code: Program that demonstrates Convert.ToInt64()  in C#

using System;
class Example
{
   static void Main()
   {
       decimal d = 245.54m;
       long res;
       Console.WriteLine("Decimal = "+d);
       res = Convert.ToInt64(d);
       Console.WriteLine("Int64 = "+ res);
   }
}

The above program generates the following output:

Decimal = 245.54
Int64 = 246

Convert.ToSingle() Method

The ToSingle() method is used to convert a value to a single-precision floating-point:

Let us see an example:

Source Code: Program that demonstrates Convert.ToSingle() in C#

using System;
public class Example {
   public static void Main() {
       bool b = true;
       float f;
       Console.WriteLine("Bool: "+b);
       f = Convert.ToSingle(b);
       Console.WriteLine("Converted: {0} to {1}", b, f);
   }
}

The above program generates the following output:

Bool: True
Converted: True to 1

Convert.ToChar() Method

Convert a specified value to a Unicode integer using ToChar() method. Let us see an example:

Source Code: Program that demonstrates Convert.ToChar() in C#

The using System;
public class Demo {
   public static void Main() {
       sbyte[] myByte = { 34, 45, 87, 101, 102, 103 };
       char ch;
       foreach (sbyte sb in myByte)
       {
          ch = Convert.ToChar(sb);
          Console.WriteLine("{0} converted to '{1}'", sb, ch);
       }
   }
}

The above program generates the following output:

34 converted to '"'
45 converted to '-'
87 converted to 'W'
101 converted to 'e'
102 converted to 'f'
103 converted to 'g'

Convert.ToDateTime() Method

To convert a given value to DateTime value, use the Convert.ToDateTime method.

Let us see an example:

Source Code: Program that demonstrates Convert.ToDateTime() in C#

using System;
public class Example {
   public static void Main() {
     string str;
     DateTime dt;
     str = "11/11/2018";
     Console.WriteLine("String = "+str);
     dt = Convert.ToDateTime(str);
     Console.WriteLine("Converted to  = "+dt);
   }
}

The above program generates the following output:

String = 11/11/2018
Converted to  = 11/11/2018 12:00:00 AM

Convert.ToInt32() Method

The Convert.ToInt32() method is to be used in C# to convert a value to a 32-bit signed integer.

Let us see an example:

Source Code: Program that demonstrates Convert.ToInt32() in C#

using System;
public class Demo {
   public static void Main() {
     double d = 25.68;
     Console.WriteLine("Double value = "+d);
     int i;
     i = Convert.ToInt32(d);
     Console.WriteLine("Converted {0} to {1}", d, i);
   }
}

The above program generates the following output:

Double value = 25.68
Converted 25.68 to 26

Convert.ToInt64() Method

The Convert.ToInt64() method is to be used in C# to convert a value to a 64-bit signed integer.

Let us see an example:

Source Code: Program that demonstrates Convert.ToInt64() in C#

using System;
public class Demo {
   public static void Main() {
     double d = 588.654;
     Console.WriteLine("Double: "+d);
     long l;
     l = Convert.ToInt32(d);
     Console.WriteLine("Converted to long = "+l);
   }
}

The above program generates the following output:

Double: 588.654
Converted to long = 589

Convert.ToSByte() Method

The Convert.ToSByte() method is used to convert a value to SByte. The SByte type is an 8-bit signed integer.

Let us see an example:

Source Code: Program that demonstrates Convert.ToSByte() in C#

using System;
public class Example {
   public static void Main() {
     double d = 30.6;
     Console.WriteLine("Double = "+d);
     sbyte sb;
     sb = Convert.ToSByte(d);
     Console.WriteLine("Converted to SByte = "+sb);
   }
}

The above program generates the following output:

Double = 30.6
Converted to SByte = 31

Convert.ToDouble() Method

The Convert.ToDouble() method is used to convert a value to a double-precision floating-point number.

Source Code: Program that demonstrates Convert.ToDouble() in C#

using System;
public class Demo {
   public static void Main() {
     long[] val = { 87687, 154416546, -8768767};
     double d;
      foreach (long a in val)
       {
            Console.WriteLine(a);
       }
       Console.WriteLine("Converted to...");
      foreach (long a in val)
       {
          d = Convert.ToDouble(a);
          Console.WriteLine(d);
       }
   }
}

The above program generates the following output:

87687
154416546
-8768767
Converted to...
87687
154416546
-8768767

Convert.ToString() Method

The ToString() method is used in C# to convert the value to its equivalent string

Let us see an example:

Source Code: Program that demonstrates Convert.ToString() in C#

using System;
public class Demo {
   public static void Main() {
       bool b = true;
       Console.WriteLine(b);
       Console.WriteLine(Convert.ToString(b));     
   }
}

The above program generates the following output:

True
True

Convert.ToBoolean() Method

To convert a specified value to an equivalent Boolean value, use the Convert.ToBoolean() method.

Let us see an example:

Source Code: Program that demonstrates Convert.ToBoolean() in C#

using System;
public class Example {
   public static void Main() {
       double d = 89.767;
       bool b;
       Console.WriteLine("Double: "+d);
       b = System.Convert.ToBoolean(d);
       Console.WriteLine("Converted to Boolean equivalent: "+b);
   }
}

The above program generates the following output:

Double: 89.767
Converted to Boolean equivalent: True

Convert.ToByte() Method

Convert a specified value to an 8-bit unsigned integer using the Convert.ToByte() method.

Let us see an example:

Source Code: Program that demonstrates Convert.ToByte() in C#

using System;
public class Example {
   public static void Main() {
       char[] ch = { 'a', 'b'};
       Console.WriteLine("Values...");
       foreach (char c in ch)
       {
         Console.WriteLine(c);
       }
       Console.WriteLine("Conversion...");
       foreach (char c in ch)
       {
          byte b = Convert.ToByte(c);
          Console.WriteLine("{0} Converted to Byte = {1} ",c, b);
       }
   }
}

The above program generates the following output:

Values...
a
b
Conversion...
a Converted to Byte = 97
b Converted to Byte = 98

Convert.ToUInt64() Method

Convert a value to a 64-bit unsigned integer using the Convert.ToUInt64() method.

Let us see an example:

Source Code: Program that demonstrates Convert.ToUInt64() in C#

using System;
public class Example {
   public static void Main() {
       char c = 'y';
       ulong ul;
       Console.WriteLine("Char: "+c);
       ul = Convert.ToUInt64(c);
       Console.WriteLine("After conversion: "+ul);
   }
}

The above program generates the following output:

Char: y
After conversion: 121

Convert.ToUInt32() Method

The Convert.ToUInt32() method is used to convert a specified value to a 32-bit unsigned integer.

Let us see an example:

Source Code: Program that demonstrates Convert.ToUInt32() in C#

using System;
public class Example {
   public static void Main() {
       string s = "30";
       uint ui;
       ui = Convert.ToUInt32(s);
       Console.WriteLine("Converted value: "+ui);
   }
}

The following is the output:

Converted value: 30

Leave a Reply

Your email address will not be published. Required fields are marked *

Suggested Tutorials

Swift Tutorial

Introduction to Swift Tutorial
Swift Tutorial

Introduction to Swift Tutorial

Read More

R Programming Tutorial

R Programming

Python Tutorial

Python Tutorial