Wednesday, January 11, 2006

C# Generics

Today isn't the first time that I've programmed using Generics in C#. But, I'm so impressed at the moment, that I just have to tell someone.

I'm currently converting my GB-PVR Solitaire plugin into a Media Center Application. (I know that Media Center already has Solitaire, but it doesn't have my Solitaire, plus I'm using this as code that I can demonstrate).

The GB-PVR plugin was written using the .NET 1.1 Framework. I'm converting to the 2.0 Framework, and I'm loving Generics!

For example, in 1.1, I used a lot of Stack and ArrayList objects. I mean A LOT (more than 10 in order to manage the state of the game as it's being played). Every time I accessed an object from one of these collections, I had to cast it to my Card type:

Stack column = Columns[col] as Stack;
Card c2 = (Card)column.Pop();

This made the code quite ugly, because these casts were happening all over the place. Well, with Generics, I can use the type Stack<Card>, and all of my type checking is done at compile time. This greatly simplifies the code:

Stack<Card> column = Columns[col];
Card c2 = column.Pop();

Or, if I don't need to reference the variable "column" any futher, then I could just do:

Card c2 = Columns[col].Pop();

And compile-time type checking totally kicks the ass of run-time type checking, especially in a strongly typed language like C#.

But, there is an apparent downside. It looks as if Generic collections do not implement ICloneable, like the old Object versions do. So, I have to think about workarounds for some of the things that my code does.

A reminder to people in the Toledo, Ohio area: Bill Wagner (Regional Director, Author) will be presenting to the NW Ohio .NET User Group on this very topic (January 31, 2006 at 6PM in downtown Toledo).

Upcoming meeting information: