tmm360
tmm360

Reputation: 414

Base generic class with automatic T from inherited son type

I've a situation like this

abstract class Foo<T>
{
    // Implementation using T type...
}
class Bar : Foo<Bar>
{ }

Every class that inherits from Foo uses itself as generic Type, and I have various inherited classes, ex: "Bar1", "Bar2", etc...

Is possible to implement the Foo class taking automatically the generic type from the inherited class type?

Upvotes: 1

Views: 67

Answers (2)

D Stanley
D Stanley

Reputation: 152624

If you want to constrain T so that every inheritor is a Foo<T> then you can do:

abstract class Foo<T> where T:Foo<T>
{
    // Implementation using T type...
}
class Bar : Foo<Bar>
{ }

Note that it's not 100% guaranteed that any class S inheriting from Foo is a Foo<S> because you can still do:

class Quux : Foo<Bar>
{ }

Which still satisfies the generic constraint because Bar is a Foo<Bar>, however Quux is not a Foo<Quux>

Upvotes: 3

Silas Reinagel
Silas Reinagel

Reputation: 4223

If it's a common implementation, then yes. If the implementation is different for various types, then no.

For a common implementation, simply put the common behavior in the abstract base class, as per Template Method pattern.

abstract class Foo<T>
{
    public void DoStuff(T obj)
    {
       ...implementation...
    }
}

Upvotes: 0

Related Questions