Generic Constraints

So far, you’ve learned how to declare a generic type and how to use it. Although the latter operation will be your main point of contact with the world of generics, you’ll sometimes want to write your own generic type. However, up to this point, we haven’t been able to do much with a generic type parameter inside the type definition. Let’s take a look from an abstract point of view first. Consider the following piece of code:

class Foo<T> {    public void Bar(T input) {        // What can we do with T?    }}

The main question is what we can do with the input received as a parameter on Bar. For one thing, we can take the object and store it somewhere (for example, in a private field). That’s precisely ...

Get C# 5.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.