Tuesday, December 25, 2018

Type Conversion


Type Conversion:

C# is a strongly typed language; therefore every variable and object must have a declare its type. C# allows us to create variables of many types but, it does not allow us to assign the value of one type of variable into another type of variables. For example, the string cannot be implicitly converted to int. Therefore, after you declare i as an int, you cannot assign the string to it. See the code below

String str = “Hello”;

int i = str;  // throws error Cannot implicitly convert type string to int

Sometime it needs to copy a value into a variable of another type. For example, you might have an integer variable that you need to pass to a method whose parameter is typed as double. These kinds of operations are called type conversions.

Type casting or type conversion refers to change of type of variable from one type to another type. Type conversion is possible if both the data types are compatible to each other.

There are two types of conversion in C#:

           1.     Implicit Conversion
           2.     Explicit Conversion

Implicit Conversion:

Implicit conversion is being done automatically by the compiler. 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, are conversions from smaller to larger integral types and conversions from derived class to base class. It doesn't require any casting operator or special syntax. The conversion is type safe and no data will be lost.

For Example:

int smallnum = 4500;

long bigNum = smallnum;                                     // Implicit conversion

In the above statements, the conversion of data from int to long is done implicitly.

Following table shows C# supported implicit conversion:



Explicit Conversion:

Explicit conversion is being done by using a cast operator. It includes conversion of larger data type to smaller data type and conversion of base class to derived classes. In this conversion information might be lost or conversion might not be succeed for some reasons. This is an un-safe type conversion.

For Example:

double y = 123;

int x = (int)y;

            In the above statement, we have to specify the type operator (int) when converting from double to int else the compiler will throw an error.




Prof. Shardul P. Patil
profshardulp.patil@gmail.com





No comments:

Post a Comment