0
0
CsharpConceptBeginner · 3 min read

What is Nullable Type in C#: Explanation and Examples

In C#, a nullable type allows value types like int or bool to hold an additional value: null. This means you can represent the absence of a value for types that normally cannot be null.
⚙️

How It Works

Normally, value types in C# such as int, double, or bool always have a value. For example, an int always holds a number, and it cannot be empty or missing. But sometimes, you want to say "there is no value" or "unknown" for these types. This is where nullable types come in.

A nullable type is like a box that can either hold a value or be empty (null). You create a nullable type by adding a question mark ? after the value type, like int?. This tells C# that the variable can hold either a number or no value at all.

Think of it like a light switch that can be on (true), off (false), or broken (null). Nullable types add this extra "broken" state to value types that normally only have on/off states.

💻

Example

This example shows how to declare and use a nullable int. It prints whether the variable has a value or is null.

csharp
using System;

class Program
{
    static void Main()
    {
        int? age = null; // age can be a number or null

        if (age.HasValue)
        {
            Console.WriteLine($"Age is {age.Value}");
        }
        else
        {
            Console.WriteLine("Age is not set");
        }

        age = 25; // now age has a value

        if (age.HasValue)
        {
            Console.WriteLine($"Age is {age.Value}");
        }
    }
}
Output
Age is not set Age is 25
🎯

When to Use

Use nullable types when you need to represent missing or unknown values for value types. For example:

  • Database fields that can be empty, like a user's birthdate.
  • Optional numeric inputs in forms.
  • Flags or counters that might not be initialized yet.

Nullable types help avoid errors by explicitly allowing null and making your code clearer about when a value might be missing.

Key Points

  • Nullable types are declared by adding ? after a value type, e.g., int?.
  • They can hold either a value or null.
  • Use .HasValue to check if there is a value.
  • Use .Value to get the actual value safely after checking.
  • They help represent missing or optional data clearly.

Key Takeaways

Nullable types let value types hold an extra null value to represent missing data.
Declare nullable types by adding ? after the type, like int?.
Always check .HasValue before accessing .Value to avoid errors.
Use nullable types when data can be optional or unknown.
They improve code clarity and safety when handling missing values.