They say the best developers are lazy. I used to believe this and would cite code reuse as justification for my inertia! For a long time now, I have been intending to use generics and collections more in my code. I guess I meant well, but in the real world we tend to go for what we know works and a syntax that we feel comfortable with. There are so many new additions to the C# langauge now that it is tempting to want to jump in and play. However, I feel that a grasp of generics is an important skill to acquire first. So, I'm going to take a walk through the generics landscape and see how it all fits together...
Here's a loose definition from a Microsoft MSDN article: "Generics are the most powerful feature of C# 2.0. Generics allow you to define type-safe data structures, without committing to actual data types. This results in a significant performance boost and higher quality code, because you get to reuse data processing algorithms without duplicating type-specific code. In concept, generics are similar to C++ templates, but are drastically different in implementation and capabilities."
Generics permit us to write code where the data types aren't hard-coded. If we have a lot of code that performs the same function but on different types, then we can get big savings in terms of performance and the amount of code that we actually have to create.
Let me say two things about generics right off the bat: first, the main motivation for generics is not one of performance. Performance is more of a side effect, if you will. It is more about what the name implies, that is, it gives a level of generality to our types. It helps us to factor out the behaviour of our classes from the data upon which they act. In addition to performance gains, we profit from increased code reuse and type safety. Second, although they share a similar motivation, generics and templates are fundamentally different animals: generics are created at runtime by the CLR and templates are created at compile time by the compiler.
The designers of generics define it as "a feature that permits classes, structures, interfaces, delegates, and methods to be parameterized by the types of data they store and manipulate." The goal of this series is to demystify generics and to encourage you incorporate it into your own code, even if only in a very basic way to begin.
In the next part, we'll take a look at some specifics including where we can use generics and and how to find our way through the new terminology associated with generics. We'll save 'Parametric Polymorphism' for a later installment ;-)