Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Default value of bool in C#
The default operator in C# returns the default value for any data type. For the bool type, the default value is false.
When a bool variable is declared without initialization, it automatically gets assigned the default value of false.
Syntax
Following is the syntax for using the default operator with bool −
bool variable = default(bool);
In C# 7.1 and later, you can also use the simplified syntax −
bool variable = default;
Using default(bool) Operator
The following example demonstrates how to get the default value of bool using the default operator −
using System;
public class Demo {
public static void Main() {
bool a = default(bool);
// default for bool
Console.WriteLine("Default for bool type = " + a);
}
}
The output of the above code is −
Default for bool type = False
Uninitialized bool Variables
When you declare a bool variable without explicit initialization, it automatically receives the default value −
using System;
public class Demo {
static bool classLevelBool; // automatically initialized to false
public static void Main() {
bool localBool = default; // C# 7.1+ simplified syntax
Console.WriteLine("Class-level bool: " + classLevelBool);
Console.WriteLine("Local bool with default: " + localBool);
Console.WriteLine("Are they equal? " + (classLevelBool == localBool));
}
}
The output of the above code is −
Class-level bool: False Local bool with default: False Are they equal? True
Comparison with Other Types
The following example shows default values for different data types including bool −
using System;
public class DefaultValues {
public static void Main() {
bool boolDefault = default(bool);
int intDefault = default(int);
string stringDefault = default(string);
char charDefault = default(char);
Console.WriteLine("bool default: " + boolDefault);
Console.WriteLine("int default: " + intDefault);
Console.WriteLine("string default: " + (stringDefault ?? "null"));
Console.WriteLine("char default: '" + charDefault + "'");
}
}
The output of the above code is −
bool default: False int default: 0 string default: null char default: ' '
Conclusion
The default value of bool in C# is false. You can explicitly get this value using default(bool) or the simplified default syntax in C# 7.1+. All uninitialized bool variables automatically receive this default value.
