Wednesday, April 20, 2016

Type Casting

The type casting is the type conversion of one data type into another data type. In C# there are two types of type casting:

Implicit Conversion

In this conversion no special syntax is required because this conversion is type safe and no data will be lost. For example, Convert small to large integer types, converting from derived class to base class
using System;
class A
{
 public int a;
 public static implicit operator B (A m)
 {
 B w = new B ( );
 w.a = m.a * 2;
 return w;
 }
}

class B
{
 public int a;
 public static implicit operator A (B w)
 {
 A m = new A ( );
 m.a = w.a / 2;
 return m;
 }
}

class Program
{
 static void Main ( )
 {
 A m = new A ( );
 m.a = 10;
 Console.WriteLine (m.a);

// Implicit conversion from A to B.
 B w = m;
 Console.WriteLine (w.a);

// Implicit conversion from B to A.
 A m2 = w;
 Console.WriteLine (m2.a);
 }
}
Output:
10
20
10

No comments: