Is there any way in C# to have a generic type that is always the implementing type in an interface? Something like this:
interface Foo
{
this GetOtherThis();
}
class Bar : Foo
{
Bar GetOtherThis();
}
Is there any way in C# to have a generic type that is always the implementing type in an interface?
No. The answers given so far don't satisfy this, for two reasons:
You can always implement an interface with a different T
interface IFoo<T>
{
T GetOtherThis();
}
public class NotAString : Foo<string>
{
string GetOtherThis() { ... }
}
This can be fixed somewhere with a constraint: interface IFoo<T> where T : IFoo<T>
but that still doesn't stop this;
public class Good : IFoo<Good> { ... }
public class Evil : IFoo<Good> { /* Mwahahahaha */ }
Inheritance breaks it anyway:
interface IFoo<T>
{
T GetOtherThis();
}
public class WellBehaved : IFoo<WellBehaved>
{
WellBehaved GetOtherThis() { ... }
}
public class BadlyBehaved : WellBehaved
{
// Ha! Now x.GetOtherThis().GetType() != x.GetType()
}
Basically there's nothing in C# which will enforce this for you. If you trust interface implementations to be sensible, then the generic interface scheme is still useful, but you need to understand its limitations.
See more on this question at Stackoverflow