Jacob Carpenter’s Weblog

April 23, 2008

C# abuse of the day: SwitchOnType

Filed under: csharp, extension methods — Jacob @ 5:30 pm

Today I encountered a situation where I wanted to switch based on a type. Maybe I stayed up a little too late reading Foundations of F#, last night.

While this is certainly no pattern matching, it didn’t seem like terrible C#:

DefinitionBase definitionBase = /*...*/;

var targetProperty = definitionBase.SwitchOnType(
        (ColumnDefinition col) => ColumnDefinition.WidthProperty,
        (RowDefinition row) => RowDefinition.HeightProperty);

Note that the lambdas require type decoration (you really don’t want to explicitly declare the generic parameters on this method).

Here’s the implementation (taking two Func projections—feel free to overload to your heart’s content):

public static TResult SwitchOnType<T, T1, T2, TResult>(this T source,
    Func<T1, TResult> act1, Func<T2, TResult> act2)
{
    if (source is T1)
        return act1((T1) source);

    if (source is T2)
        return act2((T2) source);

    throw new InvalidOperationException("No matching delegate found");
}

As you can see from the implementation, the method returns the result of the first delegate for which source can be converted into a parameter.

For a default case, add a final delegate that takes object.

About these ads

3 Comments »

  1. Cool stuff!
    Peter Hallam has a blog post on switching on types:
    http://blogs.msdn.com/peterhal/archive/2005/07/05/435760.aspx

    Also, you might find this interesting:
    http://en.wikipedia.org/wiki/Algebraic_data_types

    Comment by Kirill Osenkov — April 29, 2008 @ 11:56 am

  2. Sorry, Kirill. For some reason WordPress marked this as spam.

    Thanks for the links!

    Comment by Jacob — May 12, 2008 @ 11:54 am

  3. Embarrassingly enough, this code doesn’t actually compile. I had originally written it with a class constraint on T and used the “as” operator. I can post corrected code if anyone is interested.

    Comment by Jacob — May 28, 2008 @ 8:53 am


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

The Shocking Blue Green Theme. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: