0

I read some articles from Stackoverflow.com, especially:

What's the most concise way to get the inverse of a Java boolean value?

Easiest way to flip a boolean value?

What's happens if I have three boolean variables ? I want to assign a true/false value using single line.

For example, test1 and test3 must be true and test2 must be false.

I used

test1 = test2 ^= test3 = true;   //true, false, true

or

test1 = test3 ^= test2 ^= true;

But it not good. The logic is not good.

I know that my question is simple but I have 6-7 boolean variables and I want to assign values using single line, if is possible.

It is possible ?

Community
  • 1
  • 1
Snake Eyes
  • 16,287
  • 34
  • 113
  • 221
  • 1
    While I am intrigued to find out whether it is possible, consider readability: why on earth would you want to do such a thing? – Digitalex Aug 03 '12 at 11:24
  • What do you mean "because it is only for conditional or loop statements?" Could you post an example of this limitation? – Michael Graczyk Aug 03 '12 at 11:24
  • @Digitalex: I asked if is possible. – Snake Eyes Aug 03 '12 at 11:26
  • 2
    Why does this have to be on a single line? You could do `test1 = test3 = ... = true; test2 = test4 = ... = false;` which is only two lines. – Lee Aug 03 '12 at 11:26
  • Why is having them on one line a good thing? You are killing readability if you do that. – Oded Aug 03 '12 at 11:26
  • If you want to save lines, @Lee's solution is probably the best. An advantage is that you do not have to follow a chain of boolean expressions that may be negated multiple times, but you can just look at the right-hand side of the line to see what the values for all variables in the line are. At the same time, you are using only two lines, if you really need/want to save lines for some reason. – O. R. Mapper Aug 03 '12 at 11:28
  • Thank you for answers. Now I'm clear about this. – Snake Eyes Aug 03 '12 at 11:29
  • @MichaelSwan: You didn't just ask if it's possible - you said *wanted* to do this. Why? – Jon Skeet Aug 03 '12 at 11:30
  • `It is possible ?` (the last question)... I don't want to do. I imagined if is possible but I did mistake. – Snake Eyes Aug 03 '12 at 11:32
  • 1
    `var test = new BitVector32(5);` – Hans Passant Aug 03 '12 at 12:14

2 Answers2

0

You can do this:

test1 = !(test2 = !(test3 = true));

Although you should definitely split the assignments onto multiple lines:

test1 = true;
test2 = false;
test3 = true;

I cannot think of any place in c# in which you can do the former, but cannot do the latter.

Michael Graczyk
  • 4,905
  • 2
  • 22
  • 34
0
a = b = c = !(d = e = f = true);

This will set the first ones to false, and the second ones to true. (From D onwards.)

So in your case:

test2 = !(test1 = test3 = true);
ispiro
  • 26,556
  • 38
  • 136
  • 291