Posts Tagged ‘Templates’

Generics in .NET Part 1 – What are Generics and How to Use Them

Monday, June 29th, 2009
This entry is part of a series, Generics»

One of the most important parts of program design is making sure that your code is as reusable and maintainable as possible.  Most major developments in new programming languages tend to be aimed towards this, as well as organisation of code.  The real problem is finding different ways of creating patterns of reusable code.

One of these ways is object orientation, including polymorphism.  Whilst this is very useful, it does have some limitations.  Sometimes it is useful to be able to create a data type or a method which is almost a template – it contains or operates on or is in other way based around some other type (or multiple types), which you want to pass in when you create it.  If you are a C++ programmer, you may be familiar with this concept as templates.

As an example, in .NET 1.0/1.1, you can create a Collection, but you can’t specify what type the objects in the collection are without creating a special class for each type that you want to include in a Collection.  In .NET 2.0, if you look in the System.Collections.Generic namespace, you will find a number of different collection types that use Generics to allow you to create a collection for a specific type of item.

For example, if you want a list of dates, you can create a List(Of Date).  This will create a list that not only forces you to only put dates into it, but also intellisense will be aware that an item contained within it will be a date and will be able to eg. use the AddDays method.

If you want to use a Generic class that takes multiple type parameters, you just pass them in using the format above Type(Of TemplateTypeName), only you use commas to separate them like Type(Of T1, T2, …).  An example of this would be if you wanted to create a Dictionary(Of Integer, String), which you could use to store a lookup table of integer numbers which each have a corresponding string.

Entries in this series:
  1. Generics in .NET Part 1 - What are Generics and How to Use Them
Powered by Hackadelic Sliding Notes 1.6.5