C #: a shorter way to write v1 !? v2 :! v2

Can i write

bool v1, v2; // ... 

EDITOR: I am very sorry for the confusion. The correct statement should be:

 bool v3 = !v1 ? v2 : !v2; 

ORIGINAL I asked

 bool v3 = v1 ? v2 : !v2; 

even shorter? Or: is there an operator that will have the same result?

So, I noticed that Anders Abels answered correctly because he answered my initial question. I only need to cancel the answer.

+4
source share
3 answers

You can use xor (operator ^ ), which will give true if one and only one of the operands is true . It will return the opposite of what you want, so you need to deny everything:

 !(v1 ^ v2); 
+2
source

I think v1==v2 should do this.

Edit:

For the updated question, is v1!=v2 or v1^v2 , as Anders said.

+11
source

Vlad has already given the correct answer. I'm just adding a simple table that can help show how these problems can be solved.

  | v2 = true | v2 = false | -----------+------------+------------+ v1 = true | false | true | -----------+------------+------------+ v1 = false | true | false | -----------+------------+------------+ 

Edit: The table has been updated to reflect the updated question.

As Vlad already noted, an expression can be reorganized into != . Brackets are added for clarification. They are not needed by the compiler.

 bool v3 = (v1 != v2); 
+4
source

Source: https://habr.com/ru/post/1382688/


All Articles