4

Instead of declaring:

bool one = false;
bool two = false;
bool three = false;

Is it possible to declare something like:

bool one, two, three;

while setting them all to false ?

bool one, two, three = false
Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171
John
  • 3,965
  • 21
  • 77
  • 163
  • if you wanna make sure, that they are set to false, even if they have been set to true elsewhere - create an array of all bools, and set them to false through a foreach loop. – Stender Aug 31 '17 at 08:17

8 Answers8

7

The default value of a bool variable is false. The default value of a bool? variable is null.

For reference you can visit: bool (C# Reference).

But you cannot use it unless assigned with values.

bool one, two, three;
one = two = three = false

The same goes with nullable boolean:

bool? isCase = null;
if (isCase.HasValue){
    //TODO:
   }
Willy David Jr
  • 8,604
  • 6
  • 46
  • 57
  • 1
    That doesn't spare you assigning them if you ever want to use them. At least *my* compiler complains about *Use of unassigned variable ...*. – Filburt Aug 31 '17 at 08:27
  • Thanks, I just quote it from Microsoft Docs. I completed my explanation with codes for better understanding. @Filburt – Willy David Jr Aug 31 '17 at 08:48
4

You could either do:

bool one = false, two = false, three = false

Or

bool one, two, three;
one = two = three = false;
Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171
3

bools are false by default.

so

bool one, two, three;

Gives you three bools set to false. BUT - when you try to use them you'll get an error, eg:

Use of unassigned local variable 'three'

You need to initialise them before you use them:

bool one = false, two = false,three = false;
Jamiec
  • 133,658
  • 13
  • 134
  • 193
2

There is no built-in syntax to do that. And though bools have default value of false, C# requires you to initialze variables before you use them.

The only way I cant think of that may help you is to declare an array:

bool[] bools = new bool[3];
Console.WriteLine(bools[0]);
Console.WriteLine(bools[1]);
Console.WriteLine(bools[2]);

The array is initialized with false values, but you loose the semantics of your variable names (so I actually prefer Ashkan's answer).

René Vogt
  • 43,056
  • 14
  • 77
  • 99
1

2 Shorter ways to do that would be:

bool one = false, two = false, three = false;

Or:

bool one, two, three;
one = two = three = false;
Koby Douek
  • 16,156
  • 19
  • 74
  • 103
0

go like this:

bool one, two;
one = two = true;
CHS
  • 138
  • 1
  • 1
  • 7
0

simply, just like this:

one = two = three = false
n.y
  • 3,343
  • 3
  • 35
  • 54
0

If they are too many put them in an array and use loop. Otherwise, I think this works fine.

bool one, two, three;
one = two = three = false;
Chris
  • 7
  • 1