C# Nullable Types

In C#, nullable types allow value types to be assigned null. This is useful when a value type, such as an integer or boolean, needs to represent the absence of a value.

Key Concepts

  • Nullable types are created by adding a question mark (?) after the type, such as int? or bool?.
  • A nullable type can hold a value or null, which indicates that it has no value.
  • You can check if a nullable type contains a value using the HasValue property.

Example of Using Nullable Types

Code Example

// Declare a nullable integer
int? myNullableInt = null;

// Check if the nullable type has a value
if (myNullableInt.HasValue) {
    Console.WriteLine("Has a value");
} else {
    Console.WriteLine("Is null");
}

Output:

Is null

Code Explanation: The int? variable myNullableInt is declared as a nullable integer and initialized to null. The HasValue property is used to check if the variable contains a value. Since it is null, the program prints "Is null".

Output Explanation: Since myNullableInt is set to null, the output is "Is null". If the variable had a value, the message "Has a value" would be printed.