user9365167
user9365167

Reputation:

"in" generic modifier interaction with "where" clause

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

Upvotes: 0

Views: 56

Answers (1)

Dmitry
Dmitry

Reputation: 14059

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();

Upvotes: 1

Related Questions