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🙂