Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

class X : X<T> { } pattern in C# --- what is it used for?

Tags:

c#

generics

What is this pattern used for ? note that it is different than the C++ "curiously recurring template pattern".

like image 925
user580650 Avatar asked Oct 13 '22 17:10

user580650


1 Answers

Having the generic ancestor class know the actual descendant that inherits from it helps in scenarios where the generic ancestor needs to expose a particular non-generic descendant class as part of the non-generic descendant's result own contract.

One common example is a factory method declared in the generic ancestor:

public class Parent<T> 
    where T : Parent<T>, new
{
    public static T Create()
    {
        return new T(); // would be typically something more sophisticated
    }
}

public class Child : Parent<Child>
{
}

The primary advantage of this concept is code-deduplication.

like image 72
Ondrej Tucny Avatar answered Nov 15 '22 08:11

Ondrej Tucny