2

I want to write a lambda expression within an inline if statement. But inline if statement must have strong type results.

MyType obj = someObj.IsOk ? null : () => {
   MyType o = new MyType(intVal);
   o.PropertyName = false;
   return o;
};

Of course this doesn't work, because lambda expression isn't strongly typed. I thought of using Func<intVal, MyType> delegate, to make it strong type.

But how do I use this Func<> inside inline if? Is it at all possible of would I have to define my own function outside and use it in inline if statement?

Robert Koritnik
  • 103,639
  • 52
  • 277
  • 404
  • Well, I don't know what you will do with your saved lambda (use it locally or pass it to some other object/method). If you only use the lambda locally, I guess you should be able to get your job done with the var keyword. – Jørn Schou-Rode Jul 02 '09 at 21:16
  • I've changed my example code. The thing is I have to use constructor with parameters and also set some other property. So object initializer doesn't come into consideration. – Robert Koritnik Jul 02 '09 at 21:59
  • You can use a constructor with parameters and still set properties with an object initializer expression - see my answer for example. – Jon Skeet Jul 02 '09 at 22:08

3 Answers3

7

It has nothing to do with the lambda's typing here. You are trying to return either null or (a function taking no arguments and returning a MyType) but you are telling the compiler that the result of that statement is not a function, but just a MyType. I think what you want to do is

MyType obj = someObj.IsOk ? null : new MyType(intVal);
Mark Rushakoff
  • 249,864
  • 45
  • 407
  • 398
7

Even with the more complicated code, you can use an object initializer expression:

MyType obj = someObj.IsOk ? null : new MyType(intVal) { ProName = false };

If you really want to use a lambda though, you could write:

MyType obj = someObj.IsOk ? null : ((Func<MyType>) (() => {
   MyType o = new MyType(intVal);
   o.ProName = false;
   return o;
}))();

However, this is frankly a nightmare of brackets and casts. You can make it simpler with a helper method:

public T Execute(Func<T> func)
{
    return func();
}

...

MyType obj = someObj.IsOk ? null : Execute(() => {
   MyType o = new MyType(intVal);
   o.ProName = false;
   return o;
});
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

If you have something like this ...

  var obj = (someObj.IsOK) ? null : () => {
             return new MyType(intVal) { PropName =false }; }

You will get the error ...

"There is no explicit conversion between null and lambda expression."

The reason for that is discussed in this SO thread.

Mark is correct on what you're trying to do with the code sample, except you can set the property in like as well like this ...

var obj = someObj.IsOk ? null : new MyType(intVal) { PropName = false };
Community
  • 1
  • 1
JP Alioto
  • 44,864
  • 6
  • 88
  • 112