How it works...

Speaking of generic interfaces, we have seen that we can implement behavior on a generic class by implementing a generic interface. The power of using the generic class and generic interface is well illustrated earlier.

Having said that, we do believe that knowing when to use constraints is also important so that you can close down your generic classes to only accept specific types that you want. This ensures that you don't get any surprises when someone accidentally passes an integer to your generic class.

Finally, the constraints that you can use are as follows:

  • where T: struct: The type argument must be any value types
  • where T: class: The type argument must be any reference types
  • where T: new(): The type argument needs ...

Get C# 7 and .NET Core Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.