IT Man
IT Man

Reputation: 1036

C# interface inheritance for property

I have class like:

public interface IDriver
{
    string DriverName { get; }
    IDriverConfiguration Config { get; set; }
}

public interface IDriverConfiguration
{
    string DriverName { get; }
}

And driver class implementation:

public class MyDriver : IDriver
{
    public Configuration Config { get; set; }
}

public class Configuration : IDriverConfiguration
{
    public string DriverName { get; private set; }

    public bool EnableLogger { get; private set; }

    public int ArchiveLogs { get; private set; }
}

It seems that Config property inside MyDriver should return exact interface IDriverConfiguration instead of DriverConfiguration that inherits from IDriverConfiguration.

Is there any way to ensure that MyDriver.Config property will implement at least DriverName property?

Upvotes: 0

Views: 113

Answers (1)

Sweeper
Sweeper

Reputation: 270698

I suppose you want the Config property of MyDriver to be a more specific type - Configuration instead of IDriverConfiguration, but writing this

public Configuration Config { get; set; }

causes your MyDriver class to "not implement all the interface members" and a compiler error occurs.

Note that it is perfectly OK for you to use IDriverConfiguration here, unless you have some extra code in Configuration that you haven't shown.

What you can do is make IDriver generic:

interface IDriver<TConfig> where TConfig: IDriverConfiguration {
    string DriverName { get; }
    TConfig Config { get; set; }
}

Your implementation will be like:

public class MyDriver : IDriver<Configuration>
{
    public Configuration Config { get; set; }
    public string DriverName => Config.DriverName;
}

You can do extension methods on this like this:

public static void MyMethod<T>(this IDriver<T> driver) where T : IDriverConfiguration {

}

Upvotes: 3

Related Questions