2

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;}
}
1
  • As already provided in an answer, generics would work well here. Commented Apr 30, 2018 at 15:20

1 Answer 1

6

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;
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I have never used the out keyword here, but it's exactly what I needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.