4.4. Methods

Methods represent your point of contact with clients. As such, their flexibility, expressiveness, and general type safety should be of a great deal of importance to you. You want to make your client's life as simple as possible and, because you may likely be both the producer and the consumer of these methods, you're also likely to be especially motivated to build a good interface.

With generics, you actually have the opportunity to build a set of interfaces that are likely to last more than a few days. If you think about it, generics allow you to be 100% vague about types that are supported by your interfaces. It's as if every parameter and every return type is of the type object. All that, and you still get a type-safe interface.

Okay, that may be a bit extreme. But, if you consider that your type parameters can essentially appear anywhere within the signature of a method, it doesn't seem like that big of a stretch. At the same time, while you feel this extra degree of freedom in defining your interface, the consumers of your interface get to work with specific types without dealing with casting or conversion.


For this chapter, my focus is exclusively on generic classes. And, for that reason, the discussion of methods is intentionally constrained to how type parameters influence the methods of your class. Chapter 5, "Generic Methods," looks at generic methods that can exist entirely outside the scope of a generic class and have their own set of dynamics.

Get Professional .NET 2.0 Generics now with the O’Reilly learning platform.

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