Type Casting         
                                                                             
The rules for implicit type casting can be summarized as the following:
 
        •      It is always safe to cast from a specific type to a more generic type, for example, from
                
SalesEmployee to  Employee.
         •        It is always safe to cast from a smaller numerical type to larger one, for example, short to integer.      

Here are some examples:


static void TypeCastingTests()
{

  // Create some objects to work with.
   
  SalesEmployee sale = new SalesEmployee("Marge", "444-44-4444");
  Employee emp;

  // Cast from specific to generic. OK!

  emp = sale;

  // Casting from Employee to IPayable. OK!

  ShowPay(emp);

  // Again cast from specific to generic. Remember everything
  // derives from System.Object.

  object o = sale;

  // OOPS! Going from generic to specific yields a compile error!

  emp = o;
}

static void ShowPay(IPayable payee)
{
  Console.WriteLine(payee.ComputePay());
}


Look again at the last line of the previous example. The “o” reference is typed as object, but you know that it is
actually referring to a SalesEmployee instance. SalesEmployee derives from Employee, so technically,
emp = o
should be correct. In fact, it is, but we have to explicitly cast it.  In C#, you use syntax identical to C++ to
explicitly cast an instance to a different type.


// OOPS! Going from generic to specific yields a compile error!
emp = o;

// Works with an explicit cast.
emp = (Employee)o;


Of course, explicit casting only works if the object derives from or implements the specified type. For example,
this is an invalid cast and causes an InvalidCastException.


// Cast an employee to a car? No, runtime exception!  
Car viper = (Car)emp;


If you cannot be sure that a cast will succeed at runtime, then put the cast in a try/catch block to handle the
possible exception.


try
{
  emp = (Employee)o;
  // Use emp ...
}
catch(System.InvalidCastException e)
{
 // Handle exception ...
}


You may find it more convenient to use the is or as operators for casting. The as operator returns null if it is an
invalid cast instead of raising an exception. The
is operator evaluates whether a type can be cast to another and
returns true or false. It does not, however, perform the cast.


// as operator returns null if cast is invalid.
Employee emp = o as Employee;
if (emp != null)
{
  // use emp
}



// is operator returns true if cast is valid, false otherwise.
if (o is Employee)
{

  // You now know this is a safe cast.

  Employee emp = (Employee)o;
}

Type Casting
Table of Contents
C# Tutorial | C#.NET Tutorial | Interfaces Tutorial

Copyright (c) 2008.  Intertech, Inc. All Rights Reserved.  This information is to be used
exclusively as an online learning aid.  Any attempts to copy, reproduce, or use for training is
strictly prohibited.
Courseware
Training Resources
Tutorials
Services