- Back to Home »
- C#.NET »
- C#.NET Convertions
Posted by :
Sudhir Chekuri
Thursday, 31 December 2015
Implicit Conversion
Converting small data type values to large data type values automatically by the compiler is known as "Implicit Conversion".
Example:
int i=10;
long l=i;
Console.Write(l);//10
Explanation:
int data type is smaller than long data type ie., int data type occupies small range as compare to long data type.so conversion of int to long is possible.it is an example of implicit conversion.
Explicit conversion
Converting large data type values to small data type values explicitly by the developer is known as "Explicit Conversion".
Example
long l=10;
int i=Convert.ToInt32(l);
Console.Write(i);//10
Explanation
long data type is longer than int data type ie.,long occupies long range as compare to int.so conversion of long to int is difficult to the developer.so developer use the method Convert.ToInt32() to convert long values into int values.Then conversion is possible and easy.
C#.NET Boxing
Converting value type to reference type is known as BoxingExample
int i=10;
object o=i;
Console.WriteLine(o);//10
Explanation:
In the above example int datatype is value type.object is reference type. So, conversion of int to object is possible and it is an example of boxing.
C#.NET UnBoxing
Converting reference type to value type type is known as UnBoxingExample
object o=10;
int i=Convert.ToInt32(o);
Console.WriteLine(i);//10
Explanation
In the above example object is reference type.int is value type.conversion of object to int is not possible.so here we use Convert.ToInt32() to convert object to int.
Program to explain Implicit conversion, Explicit conversion, Boxing and UnBoxing
Program
using System;
namespace Conversions
{
class Program
{
static void Main(string[] args)
{
//Implicit conversion
int i = 10;
long l = i;
Console.WriteLine(l);//10
//Explicit conversion
long l1 = 10;
int i1 = Convert.ToInt32(l1);
Console.WriteLine(i1);//10
//Boxing - value type to reference
type
int i2 = 10;
object o2 = i2;
Console.WriteLine(o2);//10
//UnBoxing - reference type to
value type
object o3 = 10;
int i3 = Convert.ToInt32(o3);
Console.WriteLine(i3);//10
Console.ReadKey();
}
}
}
10
10
10
10