Type Conversion In C#

Type conversion which is also known as type casting is the process of converting one type of data to another one.

In C#, type casting has two forms,

  • Implicit type conversion are conversions from smaller to larger data types and conversions from derived classes to base classes.

  • Explicit type conversion are conversions from larger to smaller data types These conversions are done explicitly by users because the user needs to be aware that he might lose some data.

But, let us have a look at some code.

For built-in numeric types, an implicit conversion can be made when the value to be stored can fit into the variable without being truncated or rounded off.

For example a conversion from integer to double or from int to long.

  1. int num = 2147483647;  
  2. long newNum = num;  

 In this case the compiler implicitly converts the value on the right to a type long before assigning it to newNum.

You can do the same for base classes as well.

However, if a conversion cannot be made without a risk of losing information, the compiler requires that you perform an explicit conversion, which is called a cast.

A cast is a way of explicitly informing the compiler that you intend to make the conversion and that you are aware that data loss might happen.

For example a conversion from double to integer requires a cast.

  1. double x = 1234.7;  
  2. int a;  
  3. a = (int)x;  

 

The same is true when you convert a base class to a specific one.

Note
If you want to learn more about C# check out the full playlist of C# – Beginner to Advanced tutorials. If you like the tutorials do not forget to let me know on the comments section and subscribe for more! 

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now