Using C# Generics
I've often written about some of the big themes in modern software development: cross-cutting concerns, loose coupling, polymorphism, and so on. Knowing about these areas and concepts is crucial. Another important area—and a relative newcomer to the C# language—is generics, also important in the Java language.
One of the underlying principles of C# generics is what's known as late binding. This simply means that, with generics, the ultimate type is not bound until runtime. In other words, compile-time checks are made, but the final binding only occurs at runtime. This design provides for enhanced flexibility in class definitions.
This all sounds very complicated, but it isn't, and we'll soon be getting into the nuts-and-bolts of C# generics. Before that, it's useful to think a little about generic code in general.
Generic Code: The Holy Grail of Programming
A generic piece of code is applicable to a wide range of uses. An example of generic code is a shared library. The more generic you can make a piece of code, the more broadly useful that code will be. However, generic code is also hard to write! So, it's fair to say that creating generic code is a challenge, and it's a most useful quality attribute. The key point in this article is that if your programming language of choice (C#, in this case) supports some generic mechanisms, then it's well worthwhile coming to grips with them.
Let's get started by looking at some generic code using C# generics.