Jeff Adkins' WebLog

Sr. Software Design Engineer, Microsoft

CSharp Bits:Base/Derived Conversions

CSharp Bits is a tutorial-based digest that explains the C# programming language. It evolves, covering prerequisite topics and is currently broad in coverage rather than getting deep into a specific topic. That will come after a basis has been established.  I issue the topics daily (:p), and mainly cover one topic in each issue, so readers can fit it in their daily routine.  I email these topics internally at Microsoft and have been asked to blog the digests externally to reach out to the user community.

 

All code examples are meant to demonstrate the topic only. It is neither shippable nor secure code by any stretch of the imagination.  An archive of the topics I submitted internally within Microsoft before I started blogging these out is not currently available externally.

==

 

Base/Derived Conversions

You can convert a reference to an object of a derived class to an object of its base class, and vice versa, under certain conditions.

Conversion to Base Class Reference

References to objects of one class type can be converted into references to another type if one class inherits from the other, either directly or indirectly.

A reference to an object can always be converted to a reference to a base class object. This conversion can be performed implicitly (by assignment or as part of an expression) or explicitly (by using the cast operator).

The following examples will use two classes: Animal and Bird. Animal is the base class of Bird, or, to put it another way, Bird inherits from Animal.

The following example declares a variable of type Animal and a variable of type Bird:

Animal a;
Bird b = new Bird(...);

Now consider the following assignment, in which the reference in b is copied to a:

a = b;

The Bird class inherits from the Animal class. Therefore, a method that is found in Animal is also found in Bird. (The Bird class might have overridden some of the methods of Animal to create its own version of them, but an implementation of the method will exist nonetheless.) Therefore, it is possible for references to Bird objects to be assigned to variables containing references to objects of type Animal.

In this case, C# performs a type conversion from Bird to Animal. You can explicitly convert Bird to Animal by using a cast operator, as shown:

a = (Animal) b;

The preceding code will produce exactly the same result.

Conversion to Derived Class Reference

You can convert a reference to a derived type, but you must explicitly specify the conversion by using a cast. An explicit conversion is subject to run-time checking to ensure that the types are compatible, as shown in the following example:

Bird b = (Bird) a; // Okay

This code will compile successfully. At run time, the cast operator performs a check to determine whether the object referred to is really of type Bird. If it is not, the run-time InvalidCastException is raised.

If you attempt to assign to a derived type without a conversion operator, as in the following code, the compiler will display an error message stating, "Cannot implicitly convert type 'Animal' to 'Bird.'"

b = a; // Will not compile

You can trap a type conversion error by using try and catch, just like any other exception, as shown in the following code:

try {
  
b = (Bird) a;
}
catch (InvalidCastException) {
  
Console.WriteLine("Not a bird");
}

Published Monday, March 15, 2004 12:34 PM by Jeff Adkins
Filed under:

Comments

 

Chris Sauer said:

the following program is just what you wrote but it gives the run-time InvaldCastException

using System;
namespace ConsoleApplication7
{
public class Animal
{}
public class Bird: Animal
{}
class Class1
{
[STAThread]
static void Main(string[] args)
{
Animal A = new Animal() ;
Bird B = (Bird)A ;
}
}
}
June 28, 2004 5:06 AM
 

Chris Sauer said:

i just read an article on http://msdn.microsoft.com/msdnmag/issues/1000/dotnet/
here is said (see figure 2 in that article) (down)casting from base to derived is possible if that base is an (up)casted derived, not just a base.
reading my test main program as:
//Animal A = new Animal () ; // InvalidCastException
Animal A = new Bird () ; // OK
Bird B = (Bird) A ;
showed the "msdnmag/issues" article was correct.

But this does not solve my problem:
i have a class derived from System.Diagnostics.Process which i want to use for new and existing processes. new processes is (of course) no problem, but for existing processes one has to use the static base members GetProcess..., which return a base (Process) class and not the derived one.
June 28, 2004 1:53 PM
 

Jeff Adkins WebLog CSharp Bits Base Derived Conversions | bird baths said:

June 14, 2009 10:54 AM
 

Jeff Adkins WebLog CSharp Bits Base Derived Conversions | patio umbrella said:

June 17, 2009 11:41 PM
Anonymous comments are disabled

© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Microsoft
Page view tracker