Skip to content
November 19, 2009 / Thomas Danemar

Verbose Type Checking Must Die!

Ever since taking the plunge into the WPF world, I’ve found myself doing type checking more and more often, especially when using the MVVM (Model-View-Viewmodel) or MVP (Mode-View-Presenter) patterns. The main reason being the loosely typed nature of WPF databinding.

Our presenter/viewmodel code would be littered with snippets like this:

if (obj is SomeObject)
{
	var someObject = (SomeObject)obj;
	someObject.SomeProperty = true; // or whatever we want to do
}

Ew. Type checking data objects, then casting. Over and over again.

I believe that whenever you find yourself typing the same line of code you just typed minutes before, that’s your queue to take a pause and think about if there may be a better way of doing it. And, of course, there is, with a little help from extension methods and C# generics:

public static class Extentions
    {
        public static MyDataObject DoIfType<T>(this MyDataObject obj, Action<T> action)
		where T : MyDataObject
        {
            if (obj is T)
            {
                action((T)obj);
            }
            return obj;
        }
}

Here “MyDataObject” is the base class for all our data objects.

This lets us remake the first snippet like so:

obj.DoIfType<SomeObject>(s => s.SomeProperty = true);

Or if our intention is to pass SomeObject to another method:

obj.DoIfType<SomeObject>(AnotherMethod);

Serenity at last! I think this is cleaner and a lot more legible than the code we started with.

Advertisements

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

%d bloggers like this: