Home > Articles > Programming > C#

  • Print
  • + Share This
Like this article? We recommend


Generics represent an important but relatively recent addition to the C# language (first added in C# 2005). This useful addition mirrors the equivalent mechanism in Java. The reason that generics are interesting is not only because of the massive code savings that can be achieved—careful use of generics also allows for more generic code! In other words, you don't have to keep reinventing the wheel. An example of this principle is generic collections. The final type is created at runtime rather than at compile time.

Generic classes also provide the usual features of inheritance, interface implementation, and so forth. You simply insert the required type at runtime, and the class instance is correctly bound.

The System.Collections.Generics namespace includes a wide range of useful types in addition to List. Each of these types is worthy of study. List instances can also be sorted and searched, without the need to create special methods. In other words, the hard work of writing the sort and search code is already done for you, so you can get on with defining your application logic. The List type also provides a suite of useful properties and methods, such as Count, which returns the number of elements in the collection.

Specific base type information can be provided via the default keyword. This approach allows you to strip down an object and return its most basic expected value; for example, False for a Boolean type.

In summary, generics provide a powerful tool to the C# programmer. I've only covered a basic introduction here, but I hope that this is enough to get you started with your own investigations.

  • + Share This
  • 🔖 Save To Your Account