0

I am learning about conditional operators. The documentation mentions

condition ? consequent : alternative

From my example, Test1() is the current method that works, but I wanted to write the equivalent using conditional operators shown in Test2().

  public void Test1(bool isTrue)
  {
     if (isTrue)
     {
        MethodA();
     }
     else
     {
        MethodB();
     }
  }

  public void Test2(bool isTrue)
  {
     isTrue ? MethodA() : MethodB();
  }


  public void MethodA()
  {
     //Do This
  }

  public void MethodB()
  {
     //Do That
  }

I am receiving an error for Test2()

"isTrue" is a variable but used like a type

and

Local Function 'MethodA()' must declare a body because it is not marked 'static extern'

Can someone explain why this is the case?

janw
  • 8,758
  • 11
  • 40
  • 62
Qma
  • 111
  • 1
  • 8

2 Answers2

3

This won't work, since you cannot use ternary expressions with void return values. Use an if statement instead, as in Test1.

Also, even if the return type of MethodA and MethodB wasn't void, you always have to use the return value of the ternary, since it isn't a statement like a function call, which can stand by itself.

Thus, your Test2 method should look like this (assuming a return type T of MethodA and MethodB):

public void Test2(bool isTrue)
{
    var tmp = isTrue ? MethodA() : MethodB();
}

or

public T Test2(bool isTrue)
 => isTrue ? MethodA() : MethodB();

The compiler error in MethodA should be a direct result of the invalid body of Test2.

janw
  • 8,758
  • 11
  • 40
  • 62
0

This conditional operator uses for assigning value to variable. For example

Public bool DoSomeThing() {return true;}
Public void main() {
    String message= doSomeThing()?  "Succeed" :"Failed" ;
    ... 
    } 
    

For this example,in line No.1 we give result from doSomeThing method that it is bool type. If result be true, message variable get "Succeed" value and if that gets false, message variable gets "Failed". That was only a simple example for using of this operator that indeed use for assigning value to variable while In your code, you want execute a method that this operator isn't appropriate for your scenario.

Ali Taheri
  • 187
  • 2
  • 16