Covers topics on the Microsoft Certification Exam for the .NET Framework (Exam 70-536, Microsoft .NET Framework - Application Development Foundation)

Saturday, March 8, 2008

Using constraints with generics

Generics are less useful if you must write code that works with ALL objects because you would be limited to to the capabilities of the base Object class. Constraints allow you to limit the types of objects the caller can use. This additional information allows you (and the compiler) to make greater assumptions about which capabilities are available.

Generics can be constrained in the following ways
  • Interface - Allow only types that implement the specified interface
  • Base Class - Allow only types that are descendents of (or are) the specified base class
  • Constructor - Allow only types that have a parameterless constructor
  • Reference or value type - Allows value or reference types

Additional Resources
Constraints on Type Parameters, C# (Microsoft)
Defining and Using Generics, Visual Basic (Microsoft)

No comments:

Support This Site

LinkShare  Referral  Prg