DotNet 2.0: Is a generic of a subclass a subclass of the generic of its base?

  • Thread starter Thread starter Richard Corfield
  • Start date Start date
R

Richard Corfield

And if not, why not?

For example:

If I define

List<MyClass> foo = new List<MyClass>();
List<Object> bar = (List<Object>)foo;

then I get a compile error on the second line.

The question is why? MyClass is a subclass of Object by definition.
List can only use and expose methods acting on the type its declared
at. MyClass can do anything that Object can[1], as MyClass is a
subclass of Object, so List<Object> shouldn't be able to do anything
that List<MyClass> can't.

[1] Caveat: Dot-Net allows classes to change behaviour depending on the
declared type of the variable that the caller uses to store them, but
even then I expect the behaviour here will be as expected, so this
caveat doesn't break anything.

Thanks

- Richard
 
Richard Corfield said:
And if not, why not?

For example:

If I define

List<MyClass> foo = new List<MyClass>();
List<Object> bar = (List<Object>)foo;

then I get a compile error on the second line.

The question is why?

Because then you'd be able to add bare objects to the list - which you
can't, because it's really a list of MyClasses.
MyClass is a subclass of Object by definition.
List can only use and expose methods acting on the type its declared
at. MyClass can do anything that Object can[1], as MyClass is a
subclass of Object, so List<Object> shouldn't be able to do anything
that List<MyClass> can't.

Your reasoning doesn't follow, I'm afraid. See above.
 
Oh well. There's always a catch :-) I'll go kick myself now for not
thinking of that one. (But my intentions where honorable when I tried
to cast it Officer).

I suppose the same applies to any Generic<T> that exposes a T as a
property. Will have to think again. Not being at work, I can't think at
the moment what problem I was trying to solve.

Thanks
- Richard
 
Oh well. There's always a catch :-) I'll go kick myself now for not
thinking of that one. (But my intentions where honorable when I tried
to cast it Officer).

I suppose the same applies to any Generic<T> that exposes a T as a
property. Will have to think again. Not being at work, I can't think at
the moment what problem I was trying to solve.

Thanks
- Richard
 
An interesting aside:

Object[] foo = new DataSet[5];
foo[0] = "Wibble";

Compiles, but gives an ArrayTypeMismatch exception at runtime. I could
understand it technically if Array is a non-generic, and the compiler
is giving us syntactic sugar, though the following:

String[] foo = new DataSet[5];

fails to compile. Also:

BaseClass[] foo = new SubClass[10]; // OK
SubClass[] bar = new BaseClass[10]; // Fail

So presumably Microsoft have allowed the rule to be excepted for
arrays, presumably for convenience.
 
Back
Top