Lets say I have a class, which implements a generic interface
public interface IItem {}
public interface IStuff<out TItem> where TItem : IItem
{
TItem FavoriteItem { get; }
}
public class MyStuff<TItem> : IStuff<TItem> where TItem : IItem
{
public TItem FavoriteItem
{
get { throw new NotImplementedException(); }
}
}
I have also one non-generic interface
public interface IFavoriteItem
{
IItem FavoriteItem { get; }
}
I’d like to make MyStuff class implement this IFavoriteItem interface. Since TItem implements IItem it seems for me, that public TItem FavoriteItem property is implementing IFavoriteItem already.
But compiler doesn’t think so, and it wants me to declare a separate IItem IFavoriteItem.FavoriteItem in MyClass. Why is it so? Isn’t c# covariance the thing that should play here and solve my problem?
Thanks
The reason for this is that
FavoriteItemofIFavoriteItemmay not beIItem, where on theIFavoriteItem, it must be anIItem. The only way to solve this is by:This will simply shortcut the call to your
TItemimplementation.A good example of where this is used quite often is with the implementation of
IEnumerable<>. These often look like this: