Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive generic type parameter in C#

I needed some help understanding recursive generics in C#.

I came across this code:

public abstract class Value<T> where T : Value<T>
{
    ....
}

public class UserId: Value<UserId>
{
}

I am confused by the part where the Value<T> is used on both sides of the where clause. Can someone please explain what the code does?

like image 437
ashwnacharya Avatar asked Mar 04 '23 07:03

ashwnacharya


1 Answers

It's known as a "Curiously recurring template pattern" . C# examples here and here. Often used for fluent syntax of interface types in order to keep the generic type "known" to the base implementation.

like image 168
Jesse C. Slicer Avatar answered Mar 12 '23 03:03

Jesse C. Slicer