Tuesday, August 22, 2006

Casting in C#

In C#, there is two ways to explicitly cast an object:
  1. Using casting operator ()
  2. Using as keyword
Following code snippet conveys 3 important points:
  1. If no constructor is specified in subclass constructor, default constructor of base class is called. So parent class should either have no constructor or should must have default constructor defined if it has other overloaded constructors.
  2. Casting using casting operator throw exception if type is mismatched
  3. Casting using 'as' keyword make object null if type is mismatched
//Code
public class A
{
public A(){Console.WriteLine("Instance of A is created.");}
public A(string str){Console.WriteLine("Instance of A is created with string: " + str);}
}

public class B : A
{
public B(){Console.WriteLine("Instance of B is created.");}
public B(string str)
{
// Automatically calls default constructor
Console.WriteLine("Instance of B is created with string: " + str);
}
}

public class C : B
{
public C(){Console.WriteLine("Instance of C is created.");}
public C(string str) : base(str)
{
// Base Class Constructor B(str) is called
Console.WriteLine("Instance of C is created with string: " + str);
}
}


public class MyClass
{
public static void Main()
{
C c2 = new C("ashish");
A a = new C();
B b = (B) a;// if (ais B) stat.type(a) is Bin this expression; else exception
C c = (C) a;
a = null;
c = (C) a;// ok ..null can be casted to any reference type
A a1 = new A();
//C c1 = (C)a1; // Generates exeception
C c1 = a1 as C;
if (c1 == null) Console.WriteLine ("c1 is null"); // print c1 is null


}
}

// Output of above code
Instance of A is created.
Instance of B is created with string: ashish
Instance of C is created with string: ashish
Instance of A is created.
Instance of B is created.
Instance of C is created.
Instance of A is created.
c1 is null

No comments: