The introduction of generics into C# 2.0 simplified many programming tasks. It especially helped in the creation of type-safe collections.
During our reworking of the Infovark data access layer, we created several generic methods to return items from our database. This allowed us to eliminate many duplicated methods and eliminate a lot of type casting. For example, before we began using generics, we had methods with signatures like this:
became this after our refactoring:
Wait a minute. All we’re doing here is wrapping all our unique methods up in a generic method! Why bother? Good question. We abandoned that approach in favor of something more sensible later on.
That’s actually not the point of this post. The point is that C# doesn’t have the ability to perform a
switch on types. See all those
if statements in our generic method? That’s how we worked around the lack of type switching. If anyone has a better approach, we’d like to hear it.
Peter Hallam’s WebLog provides more information about why C# doesn’t have the ability to switch on a type. I’m not convinced by the reasons outlined there. As one commenter noted, there’s already a type-switching construct in C#: the