When branching to select a function, it might make sense to use the ternary operator to select a function, but this is impossible. Why?
public class Demo {
You have to explicitly create the delegate of the appropriate type. Normally, you can just use demo1
to refer to a System.Action
, but that is only because the compiler can infer the type based on the usage and creates the delegate for you. In this case, the compiler doesn't know that your method should be converted to System.Action
when used within the ternary operator.
If you supply this yourself for even one of the arguments, it will work:
public Action DoesWork()
{
return branch ? demo1 : new Action(demo2);
}
Since this returns new Action
explicitly for one argument, the compiler can infer that the other should be converted appropriate to a System.Action
, and it will compile successfully.