For statically-typed and compiled languages like C#, a variable cannot be re-declared or assigned a value of another type after the variable is declared. However, sometimes you need to copy or pass these variables to another variables or methods of different datatype. In such cases, should perform type conversion.

C# offers the following types of type conversions.

  • Implicit conversions – This conversion is type-safe and requires no special code. It is performed by the compiler and no data lose occurs.
int num = 123456789;
long num1 = num;
  • Explicit conversions – These conversions require a cast operator. Explicit conversion cannot be made without a risk of losing information. A cast is a way of informing the compiler that you wish to make a conversion and you are aware about the possible data loss.
double d = 3.14; 
int a = (int)d;
Console.WriteLine(a);

Output: 3

The Convert class

The Convert class has some pre-defined methods that can be used for type conversion.

MethodDescription
Convert.ToByte()Converts the specified string to 8-bit unsigned integer.
Convert.ToSByte()Converts the specified string to 8-bit unsigned integer.
Convert.ToInt16()Converts the specified value to a 16-bit signed integer.
Convert.ToInt32()Converts the specified value to a 32-bit signed integer.
Convert.ToInt64()Converts the specified value to a 64-bit signed integer.
Convert.ToUInt16()Converts the specified value to a 16-bit unsigned integer.
Convert.ToUInt32()Converts the specified value to a 32-bit unsigned integer.
Convert.ToUInt64()Converts the specified value to a 64-bit unsigned integer.
Convert.ToChar()Converts the specified value to a Unicode character.
Convert.ToString()Converts the specified value to a string.
Convert.ToSingle()
Converts the specified value to a single-precision floating-point number.
Convert.ToDoble()Converts a specified value to a double datatype.
Convert.ToDecimal()Converts a specified value to a decimal number.
Convert.ToDateTime()Converts the specified value to a DateTime value.

Example

using System;   //Adding namespaces
namespace LearnCSharp //Namespace of the class
{
class Program //The class
{
static void Main(string[] args) //Main method
{
//Converting integer to string
int a = 10;
string b = Convert.ToString(a);
Console.WriteLine("The value of b = " + b);

//Converting string to integer
string s = "12345";
int res = Convert.ToInt32(s);
Console.WriteLine("The value of res is {0}", res);

//Converting double to integer
double d = 3.14;
int i = Convert.ToInt32(d);
Console.WriteLine("The value of i is {0}", i);
Console.ReadKey();
}
}
}

Output

The value of b = 10
The value of res is 12345
The value of i is 3