I am looking at some code and I don't understand what a particular constraint means in the following class definition:
internal abstract class Entity<T> : Entity
where T : Entity<T>
{ ... }
I don't understand what this implies about parameter type T
.
Best Answer
This is similar to the "Curiously Recurring Template Pattern" (but it is NOT the same).
It can be used (among other things) to help constraint the parameter types of methods in a derived class to the same type as the derived class itself.
Here's an interesting blog post from Eric Lippert on this subject.
The main use of this is to force classes that derive from
Entity<T>
to implement some method that accepts a parameter of the same type as the deriving class.In the following code sample, we declare in the
Entity<T>
class a methodDoSomethingWithTheSameTypeAsMe()
which accepts a parameter of typeT
.Because of the generic constraint, this will force any classes that derive from
Entity<T>
to implement a version ofDoSomethingWithTheSameTypeAsMe()
which takes a parameter of the deriving class type.This is of limited use, and it is very confusing to read, so I agree with Eric Lippert when he says you should avoid such code!