Switch Expression on Types in .Net

Do you want to create a switch statement in C# on types? And the compiler says:

“error CS0151: a switch expression or case label must be a bool, char, string, integral, enum, or corresponding nullable type”

17-04-2014 09-36-19

Yes, this is a common situation that I faced already a couple of times. And that is why I want to share my solution here:

public class SwitchType
{
 readonly Dictionary<Type, Action> _matches = new Dictionary<Type, Action>();
 private Action _default = () => { };

 public SwitchType Case<T>(Action action)
 {
   _matches.Add(typeof(T), action);
   return this;
 }

 public SwitchType Default(Action action)
 {
   _default = action;
   return this;
 }

 public void Switch<T>()
 {
   if (_matches.ContainsKey(typeof(T)))
     _matches[typeof(T)]();
   else
     _default();
 }

}

And this tests shows how to use the class:

[Test]
public void AddingIntAndStringCase_SwitchPerformsCorrectCase()
{
 Type type = null;

 var typeSwitch = new SwitchType()
 .Case<int>(()=>type = typeof(int))
 .Case<string>(()=>type = typeof(string));

 typeSwitch.Switch<string>();

 Assert.AreEqual(typeof(string), type);
}
[Test]
public void AddingStringAndInt_butSwitchingForDouble_performsDefaultSwitch()
{
  Type type = null;
  var typeSwitch = new SwitchType()
   .Case<int>(() => type = typeof(int))
   .Case<string>(() => type = typeof(string))
   .Default(()=>type = typeof(double));

  typeSwitch.Switch<double>();

  Assert.AreEqual(typeof(double), type);
}

Hope this helps :)

About weiss92

Software Developer
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s