Casting from a base class to a derived class

 

This morning a friend of mine asked me how to cast a generic list to a custom class inherited from the generic list.

Let’s suppose we have the following class:

  1. public class MyClass   
  2. {   
  3.     ...   
  4. }  

and we need a collection of instances of this class, for example using the generic List<> class

  1. List<MyClass> myCollection;  

In order to improve readability, but also save time when writing code, we are often tempted to create a non-generic class implementing the list we need – even if we usually don’t really need such class

 

  1. public class MyCollection : List<MyClass>   
  2. {   
  3. }  

 

The problem arises when we use both the generic version and the custom version of the list in our code, and more specifically when we create an instance using the generic list and we need to pass this instance to a method expecting the custom version of the list:

  1. // This is the method we need to call   
  2. public void DoSomething(MyCollection myCollection)   
  3. {   
  4.     ...   
  5. }   
  6.   
  7. List<MyClass> myClass = new List<MyClass>();   
  8. DoSomething(myClass);                           // This doesn't work  

The code above generates an error during compilation, whereas a direct cast from List<MyClass> to MyCollection generates a runtime exception:

  1. List<MyClass> myList;   
  2. MyCollection myCollection;   
  3.   
  4. myList = new List<MyClass>();   
  5. myCollection = (MyCollection) myList;   // This generates a runtime exception  

The problem is that List<MyClass> is a base class and MyCollection is a derived class, hence there is no way to explicitly perform the cast.

Let’s forget about lists and generics for a moment. We have to classes:

  1. public class MyBaseClass   
  2. {   
  3.     ...   
  4. }   
  5.     
  6.     
  7. public class MyDerivedClass : MyBaseClass   
  8. {   
  9.     ...   
  10. }  

If I write the following code:

  1. MyBaseClass myBaseClass;   
  2. MyDerivedClass myDerivedClass;   
  3.     
  4. myBaseClass = new MyBaseClass();   
  5.     
  6. myDerivedClass = (MyDerivedClass) myBaseClass;    // This generates a runtime exception  

The last statement obviously causes a runtime exception, as a downcast from a base class to a derived class cannot be done.

Unhandled Exception: System.InvalidCastException: Unable to cast object of type 'MyBaseClass' to type 'MyDerivedClass'.
at Program.Main()

The reason is that a derived class (usually) extends the base class by adding more state objects (i.e. data members). When we create an instance of a base class, its data members are allocated in the memory, but of course data members of inherited classes are not allocated. So, downcasting from a base to a derived class is not possible because data members of the inherited class are not allocated.

But if we instantiate MyBaseClass as MyDerivedClass the cast is allowed – in other words downcasting is allowed only when the object to be cast is of the same type it’s being cast to:

  1. myBaseClass = new MyDerivedClass();   
  2.     
  3. myDerivedClass = (MyDerivedClass) myBaseClass;  

This because myBaseClass, although being a variable of type MyBaseClass, is a reference to an instance of MyDerivedClass.

In our problem, MyBaseClass is List<MyClass> and MyDerivedClass is MyCollection, so we are trying to cast an instance of a base class to an instance of a derived class. It’s evident why the cast we want to do is not allowed.

So, is there a solution? If we think in terms of casting, the answer is NO. What we can do is a conversion.

The difference between cast and conversion is that the cast operates on the same object instance, whereas a conversion creates a new copy.

We might think about implementing a conversion operator, either implicit or explicit, for instance:

 

  1. public class MyCollection : List<MyClass>   
  2. {   
  3.     public static implicit operator MyCollection(List<MyClass> myClass)   
  4.     {   
  5.         ...   
  6.     }   
  7.     ...   
  8. }  

 

but it won’t work, as the compiler generates a CS0553 error

 

'conversion routine' : user defined conversion to/from base class
User-defined conversions to values of a base class are not allowed; you do not need such an operator

The reason why the compiler denies such conversion is that the explicit cast operator from a base to an derived class is automatically generated, and we can’t override it with a new conversion operator.

The only viable solutions are either defining a copy constructor or implementing a method in the derived class which converts the base class to an instance of the derived class:

 

  1. public class MyCollection : List<MyClass>      
  2. {      
  3.     // Copy constructor      
  4.     public MyCollection(List<MyClass> myList) : base (myList)      
  5.     {      
  6.         ...      
  7.     }      
  8.           
  9.     // Conversion method      
  10.     public static MyCollection ToMyCollection(List<MyClass> myList)      
  11.     {      
  12.         ...      
  13.     }      
  14. }    

 

In both cases, anyway, the conversion implies the creation of a new instance of the object to be converted.

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值