Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can interface implementation member be of a derived class of interface member

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?)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>>;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading