A boolean (bool
) can't be null. And:
bool foo; if(foo){} // Use of unassigned local variable 'foo'
Why the default value is not false? So what is the value if it is not null? What is the reason?
Edit 1 - The default value is indeed false - but all variable should be initialized, why? this is for another question ;)
Edit 2 - with Resharper : private bool foo = false; // Initializing field by default value is redundant
???
This question is related to
c#
Try this (using default keyword)
bool foo = default(bool); if (foo) { }
It can be treated as defensive programming approach from the compiler - the variables must be assigned before it can be used.
The default value is indeed false.
However you can't use a local variable is it's not been assigned first.
You can use the default keyword to verify:
bool foo = default(bool);
if (!foo) { Console.WriteLine("Default is false"); }
Basically local variables aren't automatically initialized. Hence using them without initializing would result in an exception.
Only the following variables are automatically initialized to their default values:
The default values are as follows (assigned in default constructor of a class):
As far as later parts of your question are conerned:
The default value for bool is false
. See this table for a great reference on default values. The only reason it would not be false when you check it is if you initialize/set it to true.
Source: Stackoverflow.com