Dec 31, 2013

C# Switch statement alternative

You can use a Dictionary to create a mapping of Condition => Action.


 

This technique is not a general alternative to switch statement.
Suppose you have a workflow system that is required to perform validation of a data item. Different validation routines are executed based upon some state of the data being processed. Using this technique means
a) You do not have a switch statement with over 100 case statements - very difficult to read.
b) You do not have to include conditional logic in the case statement for each validation routine - very difficult to maintain.
c) You can offload the validation routines and conditional logic into a database where the customer can then update when a validation routine executes as per their requirements - very flexible.

No comments:

Post a Comment

Be the first to comment on this post.