WF4 Activities - Switch

Today I’m looking at the Switch activity.  This activity does graphically just what the switch keyword does in C#.  For you VB guys out there that’s the Select Case statement.  The behavior of Switch is very much like you would expect.  For example consider the following C# code

 int value = Convert.ToInt32(Console.ReadLine());

switch (value)
{
    case 1:
        Console.WriteLine("The value is one");
        break;
    case 3:
        Console.WriteLine("The value is three");
        break;
    default:
        Console.WriteLine("I don't know what that value is");
        break;
};

Some obvious things occur here.  First of all the Switch statement evaluates an expression of some type.  In this case the expression is simply the variable named value which is of type int.

Secondly the values in the case statement must be of the same type (or be able to be converted implicitly to the same type ) as the expression in the switch statement.

We can duplicate this logic with the Switch<T> activity.

When you drop a Switch<T> activity the Workflow Designer will prompt you to select a type argument for the expression

image

After you drop the Switch<T> you simply enter the expression you want to switch on and the case values you want to match with.

image

The Switch activity allows you to then drop other activities under each Case.  In the example above I’ve simply dropped a single WriteLine.  If you wanted something more complex you can drop a Sequence or FlowChart under the case label and then use more activities.

What kind of types can I use?

C# and VB won't let you use complex types like a Person in a switch statement. The Switch activity will allow this as long as you jump through some hoops to do it. Essentially you have to choose some property of the type to identify it. While this is allowed I don't recommend it. Instead I recommend that you use that simple property of the type in the expression as in Person.Name. If you really want to see how to do it see Usage of the Switch Activity with Custom Types and the Switch sample from the WF SDK samples.