AlphaModder
AlphaModder

Reputation: 3386

Create an interface with a method that's 'generic', but it's generic type is the implementer of the interface

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();
}

Upvotes: 0

Views: 85

Answers (2)

BradleyDotNET
BradleyDotNET

Reputation: 61349

Yes, you could write your code using a generic interface:

interface Foo<T>
{
    T GetOtherThis();
}

class Bar : Foo<Bar>
{
    Bar GetOtherThis();
}

Note: There is no generic constraint you can put on T to make T be the implementing class. Jon Skeet explains it much better detail.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500495

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.

Upvotes: 5

Related Questions