C# Type Casting – Programming, Pseudocode Example, C# Programming Example

C# Type Casting

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 FromConvert To
sbyteshortintlongfloatdouble, or decimal
byteshortushortintuintlongulongfloatdouble, or decimal
shortintlongfloatdouble, or decimal
ushortintuintlongulongfloatdouble, or decimal
intlong, float, double, or decimal
uintlong, ulong, float, double, or decimal
longfloat, double, or decimal
ulongfloat, double, or decimal

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


Example: Conversion from int to String


Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: