2

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
1

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

I spent these days reading the few resources I found regarding CRTP with C# and I think the second line means not that T implements the interface, but that the interface can be applied on T, that is, T fulfills the internal restrictions of the interface. What do you think?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.