TechShri from Shriniwas Wani

Custom Search

06 August, 2008

Casting in C# - Down Casting and Up casting

Casting

Assume a base class Employee and its derived classes as ContractEmployee and PermanentEmployee.

Employee e = new ContractEmployee();
// Above code will work – because there is implicit Upcaste from Derived to Base class.

ContractEmployee ce = new Employee(); // Won't compile – it’s a Downcaste


This happens because the rules of substitutability says that, a derived class object can always be used in place of Parent class object (Upcasting)
Because there's no guarantee that the object supports the interface defined by the ContractEmployee class.

Therefore,
in the case of a downcast, an explicit cast is used as follows:

ContractEmployee ce = (ContractEmployee) new Employee();

But what happens if we lie and try to trick the CTS by explicitly
casting a base class to a derived class as follows?

Employee e = new Employee();
ContractEmployee c = (ContractEmployee)e;

The result is not a compile-time error, because e might have really been an upcasted. But the true nature of the upcasted object can't be known until run time.

The CLR determines the object types at run time, therefore runtime error System.InvalidCastException.

Note : The CLR determines the object types at run time only.

There is one other way of casting objects: using the as keyword.

Advantage of using this “as” keyword instead of a cast is that
- if the cast is invalid, you don't have to worry about an exception being thrown.
- What will happen instead is that the result will be null. Here's an example:

class Employee { }
class ContractEmployee : Employee { }

class CastExampleUsingAsKeyword
{
public static void Main ()
{
Employee e = new Employee();
Console.WriteLine("e = {0}", e == null ? "null" : e.ToString());

ContractEmployee c = e as ContractEmployee;
Console.WriteLine("c = {0}", c == null ? "null" : c.ToString());
}
}

You'll see the following result:
e = Employee
c = null

0 Comments:

Post a Comment

<< Home