Conditional extension method

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 πŸ™‚

3 Comments

  1. Personally I prefer the good old ?: operator.
    Perhaps what bothers me is the name of the extension method ‘If’. It’s not so obvious what it’s checking. It’s as if it’s checking its arguments, when in fact it’s checking the value of the bool object. Maybe a name like IsTrue, or even Conditional, instead of If might be more suitable. All in all, may be good for own use but not so good for class library. Just my 2 cents πŸ™‚

    Avi

    Reply

Leave a comment