Let’s go through nullable types in C# β€” a way to allow value types to represent null.


πŸ“Œ 1. What Are Nullable Types?

  • Normally, value types like int, double, bool cannot be null.

  • Nullable types allow these types to also have a null value, useful for optional data or database mapping.


πŸ“Œ 2. Syntax

There are two ways to declare nullable types:

int? nullableInt = null;     // Using ?
Nullable<int> anotherInt = null;  // Using Nullable<T>
  • int? is shorthand for Nullable<int>

  • Works with all value types (int, double, bool, DateTime, etc.)


πŸ“Œ 3. Checking for Value

Use .HasValue or compare to null:

int? age = null;
 
if (age.HasValue)
    Console.WriteLine("Age: " + age.Value);
else
    Console.WriteLine("Age is not provided"); // Output
  • .Value gives the actual value

  • Accessing .Value when null throws InvalidOperationException


πŸ“Œ 4. Using Null-Coalescing Operator (??)

  • Provides a default value if the nullable is null
int? age = null;
int displayAge = age ?? 18;  // If age is null, use 18
Console.WriteLine(displayAge); // 18

πŸ“Œ 5. Nullable Boolean Example

bool? isActive = null;
 
if (isActive == true)
    Console.WriteLine("Active");
else if (isActive == false)
    Console.WriteLine("Inactive");
else
    Console.WriteLine("Status unknown"); // Status unknown
  • Nullable booleans allow three states: true, false, null

πŸ“Œ 6. Nullable in Expressions

int? a = 5;
int? b = null;
 
int? sum = a + b; // sum is null because b is null
  • Arithmetic operations propagate null if any operand is null

πŸ“Œ 7. Summary Table

FeatureDescription
Syntaxint? x or Nullable<int> x
Checking for valuex.HasValue or x != null
Accessing valuex.Value
Default valuex ?? defaultValue
Use CaseOptional data, database fields, three-state logic (e.g., nullable bool)

βœ… Tip:

  • Use nullable types for optional fields or database-mapped value types

  • Combine with null-coalescing (??) and null-conditional (?.) operators for clean code