Switch By Type in C#

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:

  1.   public Entity GetEntity(long id, int revision) {}
  2.   public Relationship GetRelationship(long id, int revision) {}
  3.   public Resource GetResource(long id, int revision) {}

became this after our refactoring:

  1.   public T GetObject<T>(long id, int revision) where T : MetaInstance
  2.   {
  3.     Type type = typeof(T);
  4.  
  5.     if (type == typeof(Entity)) return _DatabaseHandler.GetEntity(id, revision) as T;
  6.     if (type == typeof(Relationship)) return _DatabaseHandler.GetRelationship(id, revision) as T;
  7.     if (type == typeof(Resource)) return _DatabaseHandler.GetResource(id, revision) as T;
  8.  
  9.     return null;
  10.   }

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 catch statement.

UPDATE: Switching by type is a common problem with MVC frameworks. There’s been quite a lot of discussion on Stack Overflow with regard to the best way to deal with this issue.

Related Posts

  1. Using WCF to return HTML
  2. Calling a Static Method from an Object Instance in C#
  3. Creating Dummy Targets for Configuration Objects

Leave a Reply