Reputation: 344
I defined the function
public void HogeFunc(Action<Bar> act)
{
this.act = act;
}
If I call HogeFunc, it works.
if(isFuga)
{
hogeClass.HogeFunc(null);
}
else
{
hogeClass.HogeFunc(this.MyFunc);
}
But, I'd like to call HogeFunc by using ternary operator.
So, I wrote like below
try1
hogeClass.HogeFunc(isFuga ? null : this.MyFunc);
try2
hogeClass.HogeFunc((i)=>{return isFuga ? null : this.MyFunc;});
But, there didn't work...
Could you tell me how to?
Upvotes: 0
Views: 309
Reputation: 1649
It is very simple, you are just mixing parts of the ternary operation and you need type cast.
Following code:
if(isFuga)
{
hogeClass.HogeFunc(null);
}
else
{
hogeClass.HogeFunc(this.MyFunc);
}
can be rwritten as here:
hogeClass.HogeFunc(isFuge ? (Action<Bar>)null : (Action<Bar>)this.MyFunc);
or here:
hogeClass.HogeFunc(isFuge ? (Action<Bar>)null : (Action<Bar>)(x_bar =>
{
this.MyFunc(x_bar);
}));
Upvotes: 0
Reputation: 14379
Your first try looks correct to me, however you can also call like:
isFuga ? hogeClass.HogeFunc(null) : hogeClass.HogeFunc(this.MyFunc);
Upvotes: 1
Reputation: 5462
In order to use ternary operators in C#, both results MUST return the same object type.
Try casting null
to the same return type of this.MyFunc
Upvotes: 1
Reputation: 44288
ternary operators need to return the same type from both options.
Upvotes: 1