0

Suppose the following:

interface IBase { }
interface IChild : IBase { }
interface IFace<in T> where T : IBase { }
private class MyClass : IFace<IBase> { }

void Do1()
{
    // This is fine
    IFace<IChild> impl = new MyClass();
}

void Do2<T>() where T : IBase
{
    // This is not
    IFace<T> impl = new MyClass();
}

Why is that? Isn't T in Do2 guaranteed to inherit from/implement IBase?

Edit: forgot where clause in IFace

NineBerry
  • 26,306
  • 3
  • 62
  • 93
Tefatika
  • 9
  • 2
  • Does this answer your question? [What does an "in" generic parameter do?](https://stackoverflow.com/questions/6723082/what-does-an-in-generic-parameter-do) – gunr2171 Dec 20 '21 at 15:34
  • 1
    Because the `IBase` that `MyClass` uses may not be a `T` – Charlieface Dec 20 '21 at 16:07
  • 2
    What if `IFace impl = (IFace)new MyClass();`? – Dmitry Dec 20 '21 at 16:14
  • Whenever something is 'not fine' there's an error message somewhere. That message should be included in the question so that people trying to help can understand the problem. It's there on the screen and you can share it with us. Please don't post questions like "It doesn't work" or "This is fine but this isn't" when the specific error message is right there. – Scott Hannen Dec 20 '21 at 17:35

1 Answers1

1

The following code also won't compile because T is not exactly the IBase:

IFace<IBase> x;
IFace<T> impl = x; // T is IBase, but not always IBase is T

It can be some implementation of IChild, for instance.
It may be more clear in the following code:

IFace<Animal> x;
IFace<Dog> impl = x; // A dog is an animal, but not always an animal is a dog

That's why you need an explicit cast:

IFace<T> impl = (IFace<T>)new MyClass();
Dmitry
  • 13,797
  • 6
  • 32
  • 48