Compile error when creating instance of object with generic type interface

I have an interface that receives a generic type, let's call it IFoo. That generic type is constrained to being implemented by a different interface, IBar. These two interfaces are defined as follows:

internal interface IFoo<out TBar> where TBar : IBar
{
}

internal interface IBar
{
}

I then created two classes, each implementing the interfaces created above:

internal class SpecificFoo : IFoo<SpecificBar>
{
}

internal class SpecificBar : IBar
{
}

Everything works fine, and instanciating a SpecificFoo does not generate any compile error, since covariance was used when defining the generic type IBar.

// No compile error and instantiation works!
IFoo<IBar> correctFoo = new SpecificFoo();

Since I always use the interface IFoo with the interface IBar to store new instances of derived classes, my code has variables with type IFoo scattered all over. To simplify this definition, I created a second variation for the IFoo interface:

internal interface IFoo : IFoo<IBar>
{
}

The problem is that now the instanciation of new objects is not working as previously.

// Compile error!!
IFoo incorrectFoo = new SpecificFoo();

// Cast error!!
IFoo alsoIncorrectFoo = (IFoo)new SpecificFoo();

Why is the compiler not "smart" enough to understand that IFoo or IFoo with generic type IBar are the same thing? And why does the cast not work?

Upvotes: 2

Views: 183

Answers (1)

TheGeneral
TheGeneral

Reputation: 81493

If I am understanding the problem, you will need to make SpecificFoo implement IFoo

internal class SpecificFoo : IFoo<SpecificBar>, IFoo
{ .. }

Which would allow you to

IFoo correctFoo = new SpecificFoo();
//and
IFoo<IBar> anotherFoo = correctFoo;

Upvotes: 2

Related Questions