C# Nullable Types
In C#, Nullable types are used to represent a value type (like int
, float
, bool
, etc.) that can also have a value of null
.
Value types cannot normally be assigned a value of null
because they have a default value (e.g., 0 for numeric types, false
for bool
, etc.), and null
is reserved for reference types.
Nullable types allow you to assign null
to a value type, indicating the absence of a value. The nullable version of a value type is created by appending a ?
to the value type declaration.
Here are the examples of changing non-nullable types into nullable types.
int? nullableInt = null;
bool? nullableBool = true;
double? nullableDouble = 3.14;
Here, int?
, bool?
, and double?
are nullable versions of int
, bool
, and double
, respectively. You can also use the Nullable<T>
structure to create nullable types.
Nullable<int> nullableInt = null;
To check if a nullable type has a value or is null
, you can use the HasValue
property or the null-conditional operator (?.
).
To access the underlying value, you can use the Value
property (but it's safer to use HasValue
or null-conditional operator to avoid InvalidOperationException
if the nullable type is null
):
if (nullableInt.HasValue)
{
int value = nullableInt.Value;
// Do something with the value
}
or using the null-conditional operator.
int? nullableInt = SomeMethodThatMayReturnNull();
int value = nullableInt?.Value ?? defaultValue;
Nullable types are useful in scenarios where you want to represent the absence of a value for a value type, such as when working with databases where a column allows null values or when dealing with optional parameters.