-2

Is there any difference functionally between this:

bool boolean;

and:

bool boolean = false;

?

PixxlMan
  • 69
  • 1
  • 3
  • 11
  • 1
    Possible duplicate of [What is the default boolean value in C#?](https://stackoverflow.com/questions/6855664/what-is-the-default-boolean-value-in-c) that is one of many here on SO... – Trevor Apr 15 '19 at 22:50

4 Answers4

4

It depends.

If it is a local variable, there is a difference because in the first line, the variable is not initialized, and if you try using it, it won't compile.

If it is a private field in a class, then no, there is no difference, as fields are automatically initialized in C# to their default values. The default value for a Boolean is false.

Nik
  • 1,780
  • 1
  • 14
  • 23
0

There is a difference.

Actually if you try to compile used unassigned variable, you will get compiler error.

Bojmaliev
  • 61
  • 6
0

No, if boolean isn't assigned a value the default value is false. Here's a link with more information.

schne489
  • 79
  • 1
  • 6
-1

If you try to use an unasigned variable, C# will give you a compiler error:

Use of unassigned local variable 'boolean'

It only works for fields, because C# generates a default constructor that initializes it to default(bool), and the default value for bool is false.

You can let the automatic initializer set it for you. Altough not necessary, it's also ok to make it explicit in some cases for semantic purposes.

Ortiga
  • 8,455
  • 5
  • 42
  • 71
  • _You can let the default constructor set it for you_ ah, but that would only work for a field, which you have already noted is assigned by default..? – stuartd Apr 15 '19 at 22:59