0
0
CsharpHow-ToBeginner · 4 min read

How to Use Nullable Types in C# for Safe Null Handling

In C#, you use nullable types by adding a question mark ? after a value type, like int?. This allows the variable to hold either a value or null, helping you safely represent missing or undefined data.
📐

Syntax

To declare a nullable value type, add a ? after the type name. For example, int? means an integer that can also be null. You can assign either a normal value or null to it.

Use .HasValue to check if it contains a value, and .Value to get the actual value safely.

csharp
int? nullableInt = null;
if (nullableInt.HasValue)
{
    Console.WriteLine($"Value is {nullableInt.Value}");
}
else
{
    Console.WriteLine("Value is null");
}
Output
Value is null
💻

Example

This example shows how to declare nullable variables, assign values or null, and check their state before using them.

csharp
using System;

class Program
{
    static void Main()
    {
        int? age = null;
        Console.WriteLine(age == null ? "Age is unknown" : $"Age is {age}");

        age = 30;
        if (age.HasValue)
        {
            Console.WriteLine($"Age is {age.Value}");
        }
    }
}
Output
Age is unknown Age is 30
⚠️

Common Pitfalls

One common mistake is trying to use a nullable variable directly without checking if it has a value, which causes an exception.

Always check .HasValue or compare to null before accessing .Value.

csharp
int? number = null;
// Wrong: throws InvalidOperationException
// Console.WriteLine(number.Value);

// Right:
if (number.HasValue)
{
    Console.WriteLine(number.Value);
}
else
{
    Console.WriteLine("Number is null");
}
Output
Number is null
📊

Quick Reference

FeatureDescriptionExample
Declare nullableAdd ? after value typeint? x = null;
Check if has valueUse .HasValue propertyif (x.HasValue) {...}
Get valueUse .Value property safelyint y = x.Value;
Compare to nullDirectly check for nullif (x == null) {...}
Null-coalescingProvide default if nullint z = x ?? 0;

Key Takeaways

Use ? after value types to make them nullable in C#.
Always check .HasValue or compare to null before accessing .Value.
Nullable types help represent missing or optional data safely.
Use the null-coalescing operator ?? to provide default values easily.
Avoid accessing .Value without checking to prevent exceptions.