0

I've created a class like:

class C<T> {}

Then

C<string> cs = new C<string>();
C<object> co = (C<object>)cs;

.Net throws an InvalidCastException me:

It's not possible to cast a object of type C'1[System.String] to C'1[System.Object]

Any help?

Jordi
  • 20,868
  • 39
  • 149
  • 333
  • 6
    What you are looking for is [co-variance](https://msdn.microsoft.com/en-us/library/mt654055.aspx). That is only possible with interfaces and delegates. – juharr May 23 '16 at 11:44
  • 2
    I'd expect that to fail to *compile* rather than throwing an exception. It's just not valid. A `C` *isn't* a `C`. – Jon Skeet May 23 '16 at 11:45
  • 2
    You should get a compile-time error of: `error CS0030: Cannot convert type 'C' to 'C'` – Jon Skeet May 23 '16 at 11:46
  • 2
    Just another [lion eats giraffe](http://stackoverflow.com/a/2033921/284240) question – Tim Schmelter May 23 '16 at 11:47
  • 1
    *Why* did you create such a class? What are you trying to achieve? This sounds like the XY Problem: You have an issue with X, assume the solution is Y and ask about Y when you run into trouble. If you wanted to treat generic classes in an abstract way, you should use a generic interface, not try to cast between generic classes – Panagiotis Kanavos May 23 '16 at 11:48
  • @AdrianoRepetti: No, because there's no value (other than null) for which the cast is valid. It's like trying to do `Button b = (Button) new StringReader("");`. I validated that it failed to compile, by trying it... – Jon Skeet May 23 '16 at 12:01

0 Answers0