Christian Sauer
Christian Sauer

Reputation: 10889

C# Implement derived Types of an Interface Definition?

I have an inheritance tree, which looks like this:

Foo and Bar both have an Id, as defined through an specific Id class. The id classes itself are derived from a common base class.

I would now like to write an interface which can encompass both Foo and Bar, but the compiler does not allow that, I would have to use BaseId as the type in Foo and Bar, but I would like to avoid that.

public class BaseId
{
    public string Id {get; set;}
}

public class FooId: BaseId
{}

public class BarId: BaseId
{}

public interface MyInterface
{
    public BaseId Id {get; set; }
}

public class Foo: MyInterface
{
    public FooId Id {get; set;}
}

public class Bar: MyInterface
{
    public BarId Id {get; set;}
}

Upvotes: 2

Views: 107

Answers (1)

Evk
Evk

Reputation: 101443

Generics can help here. First you define interface like this:

public interface IMyInterface<out T> where T : BaseId {
    T Id { get; }
}

And then you can implement it like this:

public class Foo : IMyInterface<FooId> {
    public FooId Id { get; set; }
}

public class Bar : IMyInterface<BarId> {
    public BarId Id { get; set; }
}

Achieving your goal to use BarId and FooId in specific classes.

Both classes are also castable to IMyInterface<BaseId> in case you are in situation where you don't know the exact id type:

Foo foo = new Foo();
// works fine
var asId = (IMyInterface<BaseId>)foo;

Upvotes: 6

Related Questions