Is there any difference functionally between this:
bool boolean;
and:
bool boolean = false;
?
Is there any difference functionally between this:
bool boolean;
and:
bool boolean = false;
?
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
.
There is a difference.
Actually if you try to compile used unassigned variable, you will get compiler error.
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.