1

This code fails to compile:

public class Component<T1>
{
    public virtual void Foo(T1 t1)
    {
        return;
    }
}

public class Panel<T1>
    where T1: Component<Panel<T1>>
{
    public void Bar() {
        Console.WriteLine("Win");
    }
}

public class MyFormPanel : Panel<MyFormPanel.Form>
{
    public class Form : Component<MyFormPanel>
    {
        public override void Foo(MyFormPanel t1)
        {
            t1.Bar();
        }
    }
}

The error given is that the the MyFromPanel.Form cannot be used as a type parameter T1 since there is no implicit reference conversion from MyFormPanel.Form to Component<Panel<MyFormPanel.Form>>

This seems confusing to me because a Form inherits from Component, where MyFormPanel is a Panel. Why is this error happening then?

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
Nick
  • 920
  • 1
  • 7
  • 21
  • 4
    Doesn't really have much to do with generics or the cycle - it's all about variance. Just because A is a type of B doesn't imply that replacing all occurrences of B with A is type-safe. If you want variance, you'll need to use interfaces and explicitly mark the type arguments as either covariant or contravariant. See https://learn.microsoft.com/en-us/dotnet/standard/generics/covariance-and-contravariance for more details :) – Luaan Aug 28 '18 at 16:10
  • It is like Luaan said: "Just because A is a type of B doesn't imply that replacing all occurrences of B with A is type-safe.". You might also want to have a look at [this](https://stackoverflow.com/q/36091583/3602352). – Aly Elhaddad Aug 30 '18 at 13:19

0 Answers0