0

Just a question in general... I'm fine with using the longhand version but from an academic viewpoint, I'm curious...

Why does the shorthand ?: not compile. It does not know how to convert lambda expression to lambda expression.

            Func<int> idProp = (personIdProperty == null) ? 
                () => Person.UserAccountId : 
                () => Person.Id;

However, when I break it out into longhand, it works just fine.

            Func<int> idProp;
            if (personIdProperty == null)
                idProp = () => Person.UserAccountId;
            else
                idProp = () => Person.Id;

Thanks in advance.

Rahul Singh
  • 21,585
  • 6
  • 41
  • 56

2 Answers2

1

I had never tried that before, but yes the lambdas could be many different types, if you explicitly cast the result then it'll work.

            Func<int> idProp = (personIdProperty == null) ? 
            (Func<int>) (() => Person.UserAccountId): 
            (() => Person.Id);
Shriike
  • 1,351
  • 9
  • 20
0

To help with inference in this case, you can pass Func through a function. This way you can even omit the explicit type definition of Func:

var idProp = (personIdProperty == null) ?
    Func(() => Person.UserAccountId) : 
    Func(() => Person.Id);

//...
private Func<T1> Func<T1>(Func<T1> f)
{
    return f;
}
George Polevoy
  • 7,450
  • 3
  • 36
  • 61