Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write strongly typed lambda expressions?

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?

like image 710
Robert Koritnik Avatar asked Dec 28 '25 00:12

Robert Koritnik


2 Answers

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;
});
like image 81
Jon Skeet Avatar answered Dec 30 '25 14:12

Jon Skeet


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);
like image 44
Mark Rushakoff Avatar answered Dec 30 '25 16:12

Mark Rushakoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!