Question

Hi guys I have the following if

if(check)
{
    count++;
    push();
}
else 
{
   count--;
   pop();
}

I would like know if it's possible transform this if in a conditional statement

Something like this:

(check)?count++,push():count--,pop();
Was it helpful?

Solution

Ternary operator requires a return value, so wrap your method in a delegate and return some dummy value(in this case true). You're done..

int count = 0;
Func<bool> func1 = () =>
{
    count++;
    push();
    return true;//To make compiler happy
};
Func<bool> func2 = () =>
{
    count++;
    push();
    return true;//To make compiler happy
};

var dummy = (check) ? func1() : func2();

OTHER TIPS

Ternary operator must return a value. So no, you can't change your conditional statement into ternary.

?: Operator

Nope, you can't do that.

It is called a "ternal operator" (?:) and it can be only used for a value assignment like

var text = cond ? "yes" : "no";

Read more about it on MSDN. Although you can do

int PushMethod()
{
   push();
   return count + 1;
}

int PopMethod()
{
   pop();
   return count -1;
}

and use it like

count = cond ? PushMethod() : PopMethod();

You can define some Count property wrapping the count like this:

public int Count {
  get { return count;}
  set {
    int i = value - count;
    count = value;
    if(i == 1) push();
    else if(i == -1) pop();
  }
}
//then do it like this
Count += check ? 1 : -1;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top