tags:

views:

112

answers:

3

Here's the problem

I'm trying to cast form List to an object MyTypes which is defined as

public class MyTypes : List<MyType> { ... }

It won't cast directly with (MyTypes) - compiler error

Or with as MyTypes - returns null

I would think this would be possible, but clearly I have to overload some casting operation.

Help!

+3  A: 

If MyTypes inherits from List you cannot cast a List if MyType.

Example this is not valid:

MyTypes foo = new List<MyType>();

This is valid:

List<MyType> foo = new MyTypes();
MyTypes bas = (MyTypes) foo;

You cannot cast a base class isntance to an inherited type, example, you cannot cast from Vehicle to Car but you can do it from Car to Vehicle (If Car : Vehicle)

AlbertEin
+1  A: 

If I understand you correctly, you have a List<MyType>, and you want to cast it to a MyTypes, which derives from (inherits) from List<MyType> ...

You can't do this... If you had a MyTypes you could cast it up the imnheritence chain to a List<MyType>. But you can't cast down the inheritence chain...

Charles Bretana
+1  A: 

You could pass your List<MyType> in as a parameter when constructing your MyTypes and then hand this off to the base class constructor..

flesh
That's what I resorted too when I realized what I wanted was impossibel
Chad
Eric Lippert writes about this kind of thing on his blog, and I'm sure he has covered this but I can't find the article at the moment, apologies. http://blogs.msdn.com/ericlippert/default.aspx
flesh