Generics: Making life easier one class at a time

I was looking forward to .Net Generics since I learned they'd be included in .Net 2.0. Having to build an entirely new class to implement a strongly-typed collection was a drag, when Collection(of..) or Collection<> would have solved the problem in a fraction of the time.

So I've been using them for typed collections, and they're great. The part I didn't anticipate was what a lifesaver they'd be in a thousand other instances.

So far, besides using them for Collections, Lists, Dictionaries, and so on, I've used Generics in places like these:

  • Building a base class to handle properties that can track Dirty. Since the property types vary, this would have meant creating them as Object before. This is much, much better syntactically, and especially with respect to type safety.
  • Abstracting me from Oracle hell. For reasons known only to the Royal Order of Oracle DBAs, local chapter #666, some of our lookup tables use Integer keys, while others use two-characters "codes". They're all the same to me, thanks to Generics. I set the ID up as a Generic type, and I'm off and running (it's slightly more complicated than this, but not by much).
  • I used Generics to wrap some common functionality around a bunch of DataSets, where the DataSets had to remain strongly-typed in order for things to work right (so I couldn't just write against DataSet).

Bottom line: once you get used to thinking in Generics, you'll find all sorts of problems that cry out for them.

One of the things you'll have to get used to is the slightly weird meta-syntax you have to deal with from within the Genericized class. You can't just use == or != for instance, becuase those operators might not be defined for all generic types.

So crack open the help files and recall how .Compare works, and while you're in there, check out the Where syntax for use when declaring your Generic class -- it lets you specify specific interfaces that you require your implemented object to support.

For example, if you want to create a class that works with any IEnumerable object, you can specify that using Where on your class declaration, and then you can use this class Generically only with objects supporting IEnumerable. This isn't too difficult to get a handle on, and it's a small price to pay for real type-safety.

If you have any questions, or you'd like to see some examples, leave a comment -- I'd love to hear from you.