A boolean (bool
) can\'t be null. And:
bool foo; if(foo){} // Use of unassigned local variable \'foo\'
Why the default value is
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 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"); }
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.
It can be treated as defensive programming approach from the compiler - the variables must be assigned before it can be used.
http://msdn.microsoft.com/en-us/library/83fhsxwc.aspx
Remember that using uninitialized variables in C# is not allowed.
With
bool foo = new bool();
foo will have the default value.
Boolean default is false
Try this (using default keyword)
bool foo = default(bool); if (foo) { }