C#/C# Tutorial

C# Nullables | C# Tutorial for Beginners

DragonTory 2023. 2. 14. 21:16
반응형

 C# Nullables 

 

C# nullable types were introduced to allow variables to have a value or a null reference. 

In C#, by default, value types (such as int, double, and bool) cannot be assigned a null value. 

Nullable types allow you to assign a null value to a value type by wrapping the value type in a Nullable<T> structure.

To declare a nullable type, you can use the ? modifier after the value type.

 For example, to declare a nullable int:

int? nullableInt = null;

 

You can also use the Nullable<T> structure to declare a nullable type:

Nullable<int> nullableInt = null;

 

You can check if a nullable type has a value or is null using the HasValue property:

if (nullableInt.HasValue)
{
    int intValue = nullableInt.Value;
}
else
{
    // nullableInt is null
}

 

You can also use the null-coalescing operator (??) to assign a default value to a nullable type if it is null:

int nonNullableInt = nullableInt ?? 0; // nonNullableInt is 0 if nullableInt is null

 

You can use the GetValueOrDefault() method to get the value of a nullable type, or a default value if it is null:

int nonNullableInt = nullableInt.GetValueOrDefault(); // nonNullableInt is 0 if nullableInt is null
int nonNullableInt = nullableInt.GetValueOrDefault(10); // nonNullableInt is 10 if nullableInt is null

 

Note that when you use a nullable type in an expression, you may need to use the Value property to get the underlying value, as the nullable type is not implicitly converted to the value type:

int? nullableInt = 10;
int intValue = nullableInt.Value; // intValue is 10
반응형