C# nullable types
In C#, a nullable type is a value type that can also have a value of null
. A value type, such as an integer (int
), double (double
), or boolean (bool
), is a type that represents a value rather than a reference to an object. By default, value types cannot be null
.
Nullable types are useful when you need to represent situations where a value might be missing or unknown. For example, if you have a database field that can contain a number or no value at all, you can use a nullable integer (int?
) to represent that field.
To create a nullable type in C#, you use the ?
character after the data type. For example:
int? nullableInt = null; double? nullableDouble = 3.14; bool? nullableBool = false;Sourec:www.theitroad.com
Here, nullableInt
has no value (null
), nullableDouble
has a value of 3.14, and nullableBool
has a value of false
.
You can also use the Nullable<T>
struct to create a nullable type. For example:
Nullable<int> nullableInt = null; Nullable<double> nullableDouble = 3.14; Nullable<bool> nullableBool = false;
To access the value of a nullable type, you can use the Value
property or the null coalescing operator (??
). For example:
int? nullableInt = 10; int intValue = nullableInt.Value; // intValue is 10 int? nullableInt2 = null; int intValue2 = nullableInt2 ?? 0; // intValue2 is 0
In the first example, intValue
is assigned the value of nullableInt
, which is 10
. In the second example, intValue2
is assigned the value of nullableInt2
, which is null
, so the null coalescing operator assigns the value 0
to intValue2
.
Note that you cannot use the Value
property on a nullable type that has no value (null
), as it will throw a InvalidOperationException
.