C#-Using a Dictionary to switch

Run different actions for different types

Switch statements are a great way to run different actions for different values. It’s easy to use and it’s pretty simple to scale if new values are added. But what would you do if you want to e.g run custom actions for types and subtypes easily?🤔

There is a neat way to do so.
In .Net you can create your own dictionary that works like a switch. Not only for Types as a distinction.

Creating the dictionary

Creating this dictionary is pretty straight forward. All you have to do is (obviously) create a dictionary and define the distinction type as key and use “Action” as value.

Here we created a read-only dictionary and call it @switch. In .net you are using the @-character if you want to use a reserved name. Inside the dictionary, we created three different key-value-pairs. Each pair is for a different type we want to switch through.

The only thing left to do now is to implement the three methods and call the switch dictionary e.g.

And you are good to go! 😃
Don’t forget to use a proper exception handling for the case the key does not exist in your @switch dictionary. 😉

Can I use parameter with this method??

Of course! With a few changes, you can also add parameters to the @switch dictionary. To accept a paramater you have to change the action e.g.

Thats all! Just take care you also hand the param to @switch

Thats it amigo! You have successfully created a @switch dictionary!

Leave a Reply

Your email address will not be published.