comment 0

Create a switch for ASP.Net objects

In my opinion one of the most underused tools in a coders tool belt is the “switch” statement because it can be much faster than using several “if” statements and a lot easier to read. Again just my opinion. What amazed me was when I needed to get the value from an ASP.Net control object, but I may not always know what that object was. I didn’t want to create a huge list of “if” statements just to get the right object. I wanted to use my handy dandy tool, the “switch” to make this easy. What .Net doesn’t tell you is that you can’t use the built in “switch” on objects. You are only allowed to use the built in C# switch on run-time constants. Things like strings, ints and chars. Did this stop me? Nope! I did a little searching and found that you can use a Dictionary to hold your object type then return a function that is executed for that object. Brilliant! I found the way to create a switch for ASP.Net objects, but how does it work? Well here is the code:



The above code only shows three control objects, but you get the point. The Dictionary is a key, value pair object. You pass in the key and it will return the value. In this case it will execute the function and return the value for that object.

How do I use such a dynamic thing? Well that was the question. Not only did I need to pass the type of the object, I would then need to pass the object itself. I am new to Functions so I was not real sure how this would happen. After I figured out what the syntax was it all made sense. Here is how you call the @switch:

With the Dictionary the first part in the [] is the key you are passing in. later in the call you can pass the actual control in the () just like any other method call. Like I said, once I figured this out it all made sense and was very familiar. So you can add this one more tool to your tool belt and create a switch statement for ASP.Net objects.

Leave a Reply

Your email address will not be published. Required fields are marked *