Type Conversion in C#

Type conversion is the method of converting one type of data to the another type. As we already discussed about Data Types in C# previously, sometimes it is necessary to convert the data of one type to the another type.

Type Conversion in C# are of two types.

  1. Implicit Conversion
  2. Explicit Conversion

Implicit Conversion

Implicit conversion happens when one type of data type automatically converted into the another type. One case of implicit conversion is when we assign a value of smaller data type to a bigger data type.

Also, there is no loss of data in implicit conversion.

For example, let’s say the data type int with name amount is holding a data like this,
int amount= 12000;

Now, we have a function that only accept the double value as parameter and return the actual salary after tax reduction.

The whole scenario after type conversion looks like this in code.

Here, the int type amount variable is implicitly converted into decimal type salary variable. We are not writing any extra pair of code for implicitly conversion, just assigned the decimal type with int type.

When you run the program, you can see 12000 as actual salary which mean no loss in data.

Explicit Conversion

Explicit conversion is also known as forced conversion which only happen after writing extra pair of code. Unlike implicit conversion, explicit conversion has the possibility of data loss.

Let’s make few change on previous example to understand the explicit conversion.

The amount variable is declared as double data type like this.

double amount= 12000.213;

At this point the function is changed to accept only the int value as salary and return the actual salary after tax reduction.

Now the type conversion looks like this in code.

Here the initial value is in decimal and later explicitly converted into int type with the help of built-in function Convert.ToInt32(). 

Now, run the program you will get 12000 as output which mean loss of .213.

C# has many built-in function like Convert.ToInt32() for explicit type conversion. Some of them are,

  • .ToInt16() = convert a given type into 16 bit integer type.
  • .ToInt64() = convert a given type into 64 bit integer type.
  • .ToString() = convert a given type into string type.
  • .ToBoolean() = convert a given type into boolean type.

You can read more about type conversion from here.

Tagged

About dipneupane

Dip is a passionate Software Developer based in Kathmandu, Nepal. He chew code and smash keyboard for living. Apart from that, he writes about almost everything on buzzedcode.com.

View all posts by dipneupane →

Leave a Reply

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