In short, suppose there is an interface
interface IListInterface
{
IList<int> List { get; }
}
I have a class that has a member of ObservableItemCollection which implements the IList somewhere in it’s parents:
class Model
{
ObservableItemCollection<int> List { get; }
}
Is there a way to make Model be considered IListInterface without adding explicit implementation? (e.g. following with no errors?)
class Model : IListInterface
{
ObservableItemCollection<int> List { get; }
}
>Solution :
This has actually been proposed together with the covariant return types feature in C# 9. However, it seems to have not been implemented, possibly because supporting implicit interface implementations would be a source-breaking change (See the end of this section).
Since covariant return is implemented for class methods, you can add a dummy abstract base class for Model and override the getter in that class:
abstract class ModelBase: IListInterface {
public abstract IList<int> List { get; }
}
class Model : ModelBase
{
public override ObservableItemCollection<int> List { get; }
}
Alternatively, add a covariant generic parameter to your interface:
interface IListInterface<out TList> where TList: IList<int>
{
TList List { get; }
}
class Model : IListInterface<ObservableItemCollection<int>>
{
public ObservableItemCollection<int> List { get; }
}
And you’d use IListInterface<IList<int>> everywhere, pretending the generic type doesn’t exist 🙂 Since TList is covariant, it is possible to implicitly convert a Model to IListInterface<IList<int>>.
You can even add a global using alias for this, if you really want:
global using DefinitelyNotGenericIListInterface =
YourNamespace.IListInterface<System.Collections.Generic.IList<int>>;