Chris Cavanagh’s Blog

Entries from May 2008

Conditional extension method

May 22, 2008 · 3 Comments

Here’s a nice little extension method you might find useful:

public static class ExtensionMethods
{
    public static T If<T>(
        this bool condition,
        T left,
        T right )
    {
        return condition ? left : right;
    }
}

Looks pretty useless right?  It is, unless you want to do something like this in C#:

Func<MyType, bool> predicate = myCondition
    ? v => ( v != null ) ? v.MyFlag : false
    : v => true;

Here’s where compilation will get you:

Type of conditional expression cannot be determined because there is no implicit conversion between ‘lambda expression’ and ‘lambda expression’

You can easily fix it by casting one of the expressions to the result type like this:

Func<MyType, bool> predicate = myCondition
    ? v => ( v != null ) ? v.MyFlag : false
    : (Func<MyType, bool>)( v => true );

But that’s just hideous, right? :) (it forces you to repeat yourself, it’s ugly and you can’t use ‘var’).  Enter our super slick new extension method:

var predicate = myCondition.If<Func<MyType,bool>>(
    v => ( v != null ) ? v.MyFlag : false,
    v => true );

It’s not perfect, but it’s neater.  You can even use it with expression trees:

var predicate = myCondition.If<Expression<Func<MyType,bool>>>(
    v => ( v != null ) ? v.MyFlag : false,
    v => true );

Improvements & comments welcome :)

Categories: .NET

More WPF Physics

May 15, 2008 · Leave a Comment

Fabrice Kauffmann has started a series of posts on using a physics engine with WPF, with some good code samples to get you on the right track.  You can read part 1 here, or in the original French here :)

Categories: .NET

Dead ringer

May 5, 2008 · 2 Comments

It was inevitable of course, but I’m comforted by the warranty :)

Chris birthday and 360 RRoD 004

Categories: .NET

.NET is crap?

May 5, 2008 · 2 Comments

Wow, I can’t believe I still enjoy writing .NET apps on Windows when it’s this bad.  How naive of me…  Maybe I’m just old and get a kick from dumbed-down languages (btw I turned 100011 (0×23) yesterday; yay me! :) ).

Categories: .NET