Generics Primer – Part 1

When generics were first released, the generic collections where the first place that I used them. They removed a lot of the boilerplate code when it came to creating strongly typed collections. In 1.x you would inherit from the base class of the type of collection you wanted, and then implement strongly typed versions of methods such as Add, Remove, Contains. An example of this can be found here.¬†Thanks to generics you don’t need to create a MyClass1List and a MyClass2List you can simply instantiate a new List<MyClass1>() and new List<MyClass2> without needing to write the plumbing code to have this work.

[gist id=8192633]

When .Net 3.5 was released it included one of my favorite features in .Net, LINQ which is a set of extension methods that make extensive use of generics, allowing for removal of much of the boilerplate involved with searching collections.

[gist id=8192749]

In my next post I will talk about creating some simple generic classes and methods.