Difference between ternary (conditional) operator and if statement returning an Action
c#, if-statement, ternary-operator
Solution
Why explicit cast is required in Conditional operator
_doSomething = ThisOrThat ? DoThis : DoThat;
From this answer from Jon Skeet:
as the expression. What's the type of that? What delegate type should the method groups be converted to? The compiler has no way of knowing. If you cast one of the operands, the compiler can check that the other can be converted though
For your question:
Why it is allowed in `if` statement
You are doing a simple assignment where left hand side is `Action` and the right hand side is a method group. There exists implicit conversion
See Assignment Operator(=) C#
The assignment operator (=) stores the value of its right-hand operand in the storage location, property, or indexer denoted by its left-hand operand and returns the value as its result. The operands must be of the same type (or the right-hand operand must be implicitly convertible to the type of the left-hand operand)
Problem
Consider the following code that doesn't compile: ``` class WhyNot { private Action _doSomething; public bool ThisOrThat; public WhyNot() { _doSomething = ThisOrThat ? DoThis : DoThat; } private void DoThis() {} private void DoThat() {} } ``` I understand that this doesnt work because methods dont intrisically have a type, whereas delegates do, so an explicit cast must be made. ``` _doSomething = ThisOrThat ? (Action)DoThis : (Action)DoThat; ``` What I dont follow is why then does a standard if statement succeed in casting these where the ternary operator fails? ``` if (ThisOrThat) _doSomething = DoThis; else _doSomething = DoThat; ``` Why the difference between the operators?