0

Why does following C# code produces an error:

CS0030: Cannot convert type 'Test.G<Test.C>' to 'Test.G<Test.I>'

interface I { }
class C : I { }
class G<T> { }

class B {
    G<C> a = new G<C>();

    void Test() {
        G<I> v = (G<I>)a;
    }
}
Marcel
  • 1
  • 2
  • Does https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/out-generic-modifier help? – mjwills Jun 17 '18 at 21:33
  • Go read up on C# covariance, that's why you can't do this. – DavidG Jun 17 '18 at 21:35
  • Thanks guys for pointing me to the right topic. I obviously could not find the right words when googling the problem. – Marcel Jun 17 '18 at 21:44
  • Just for your information. As I could not change the variance of the parenting interface (coming from 3rd part API) I ended up using not so elegant but effective method using dynamic. – Marcel Jun 18 '18 at 06:49

0 Answers0