Reputation: 187
I'm studying with C# in depth book and it mentions that a form of constraint uses the type parameter in the constraint itself. So what is the difference between these two:
public void Method(AClass<T> myobject) where T : ISomething //Here I say that T has to implement ISomething
public void Method(AClass<T> myobject) where T : ISomething<T> //I don't understand this
Upvotes: 2
Views: 59
Reputation: 7111
Consider that you have a non-generic interface ISomething
defined. The first line constrains T
to types that implement that interface.
Now consider that you have a different, generic interface ISomething<T>
defined. The second line says that T is constrained to types that implement that interface, but with the further restriction that the generic parameter on the interface must the set to the type that you are specifying.
For example
interface ISomething<T> { /* methods */}
class MyClass: ISomething<MyClass> { /* methods */ }
See the relationship that MyClass
has with ISomething<T>
. That's what that constraint is demanding.
C++ programmers call this the Curiously Recurring Template Pattern (https://en.m.wikipedia.org/wiki/Curiously_recurring_template_pattern). Don't worry it tends to melt everyone's mind the first time they encounter it. And, if you don't use it for a while, it's not like riding a bike; you need to learn it all over again
Upvotes: 3