Type conversion in C#:
Type conversion is a process of converting one type into another.
Using C# type conversion, not only can you convert data types but you can also convert object types.
There are mainly Two type conversion:
Implicit conversion & an explicit conversion
Implicit conversion:
If one type of data is automatically converted into another type of data, it is known as implicit conversion. There is no data loss due to implicit conversion.
Example:
long x;
int y = 100;
x = y; //implicit numerical conversion
Possible implicit numerical conversions in C# are below: -
Boxing Conversions:
Boxing is the conversion of any value type to object type. Remember that boxing is an implicit conversion. Boxing a value of value type like int consists of allocating an object instance and copying the value of the value type into that object instance. An example of boxing is shown below.
Example:
int x = 10;
object o = x; //Boxing
if(o is int)
Console.WriteLine("o contains int type");
Explicit conversion:
Explicit conversion is a forced conversion and there may be a data loss.
Type conversions occur mainly when we pass arguments to a function or mixing mode arithmetic etc.
Example:
double d = 100.15;
int i;
i = (int)d;
Now, if you print “i”, you will find that it will print “100”. All the data after the decimal will be lost in the conversion.
Un-boxing Conversions:
Un-boxing is the conversion of an object type to a value type. The casting operator () is necessary for unboxing.
Example:
int x = 100;
object o = x; // Boxing
int I= (int) o; // un-boxing