Type Casting in C#

C# is statically typed at compile time. It means when we declare a variable we cannot declare it again or cannot store data of another data type unless we implicitly change the data type of that variable. This type of conversion operation of a data type is called typecasting.

In c# we can perform the following type of conversion.

  • Implicit conversion
  • Explicit conversion
  • User-defined conversion
  • Conversion with a helper class

Implicit conversion

C# provides integral which can convert data type within two numeric types. The following table will show the predefined conversion through implicitly

Convert From Convert To
sbyte shortintlongfloatdouble, or decimal
byte shortushortintuintlongulongfloatdouble, or decimal
short intlongfloatdouble, or decimal
ushort intuintlongulongfloatdouble, or decimal
int long, float, double, or decimal
uint long, ulong, float, double, or decimal
long float, double, or decimal
ulong float, double, or decimal
float double

But there’s a risk of the loss of information during the implicit conversion of the data type.

Explicit Conversion

If we don’t want to lose information during conversion, we will use explicit conversion complier require that you perform conversion of data type which is called a cast.

Following are some examples of method built-in method for the conversion of the data type.

  • Convert.toInt32
  • Convert.toDouble
  • Convert.ToString
  • Convert.ToBoolean
  • Convert.ToSbyte
  • Convert.ToDateTime
  • Convert.ToInt16

Example: Conversion from String to int

string Numbers = "10";
int Converted_Number =  Convert.ToInt32(Numbers);
Console.WriteLine(Converted_Number);

Output:

10

Example: Conversion from int to String

int Numbers = 10;
string Converted_Number =  Convert.ToString(Numbers);
Console.WriteLine(Converted_Number);

Output:

10