3

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
  • 32,319
  • 30
  • 98
  • 161
John
  • 3,853
  • 20
  • 69
  • 146
  • 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
  • 7,817
  • 5
  • 40
  • 51
  • 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
  • 32,319
  • 30
  • 98
  • 161
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
  • 128,537
  • 12
  • 134
  • 188
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
  • 41,709
  • 14
  • 73
  • 93
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
  • 15,427
  • 16
  • 64
  • 91
0

go like this:

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

simply, just like this:

one = two = three = false
n.y
  • 3,131
  • 2
  • 34
  • 51
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