Why can I not convert a Foo<Bar>
to IFoo<IBar>
.
If I try I get:
There is no implicit reference conversion from
Foo<Bar>
toIFoo<IBar>
It would work if you were using C# 4 and IFoo
were declared as:
public interface IFoo<out T>
assuming that Bar
implements IBar
and Foo<T>
implements IFoo<T>
.
However, it could only be declared that way if it were safe. It's not safe if T
values "go into" the API as well as coming out. For example:
public interface IFoo<T>
{
T Value { get; set; }
}
This can't be covariant in T, as otherwise you could write:
public class StringFoo : IFoo<string>
{
public T Value { get; set; }
}
IFoo<string> fooString = new StringFoo(); // That's fine
IFoo<object> fooObject = fooString; // This isn't, because...
fooObject.Value = new Object(); // ... this would violate type safety
Read Eric Lippert's long blog series on generic variance for much more information.
In order for this to work, three things need to be true:
Bar
must implement IBar
Foo
must implement IFoo
IFoo<T>
must be covariant in T
(like this: IFoo<out T>
)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With