C# - 21 - Fun with Switch statements

[C# 3.5]

One 'problem' with switch statements in C# is that thay need to be constants or enums. Consider the following scenario:

Here there is an object (called MyDataObject) with a property (called PersonScenario) and you want to test that in a switch statement. This won't compile as the compiler insists on each case statement being for a constant or enum, and what we have here is a variable (albeit derived from an enum).

The solution is first to modify the enum to have a 'default' value. Lets call it 'Anybody'.

Then add a second property to the data object that is derived from the same underlying data. (In this case PersonScenario was derived from _PersonScenario.)

So finally the switch statement can be rewritten:

.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License