10.6. Constraining Type Parameters
As this chapter illustrates, any generic item has at least one type parameter that you need to specify at the time you interact with the generic type or member. This alone allows you to build some type safe code; however, the .NET platform allows you to use the where keyword to get extremely specific about what a given type parameter must look like.
Using this keyword, you can add a set of constraints to a given type parameter, which the C# compiler will check at compile time. Specifically, you can constrain a type parameter as described in Table 10-6.
Generic Constraint | Meaning in Life |
---|---|
where T : struct | The type parameter <T> must have System.ValueType ... |
Get Pro C# 2010 and the .NET 4 Platform, Fifth Edition 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.