0
0
CsharpConceptBeginner · 3 min read

Nullable Struct in C#: What It Is and How It Works

A Nullable<T> struct in C# allows value types like int or bool to hold an additional null value, meaning they can represent 'no value'. It is useful when you need to distinguish between a default value and the absence of a value.
⚙️

How It Works

In C#, value types such as int, double, or bool normally cannot be null. They always have a value, even if it's the default like 0 or false. But sometimes, you want to say that a value type has no value at all, like an empty box.

The Nullable<T> struct acts like a special box that can either hold a value of type T or be empty (null). This is like having a light switch that can be on (true), off (false), or missing (null) to show it's not set.

You can create a nullable value type by adding a question mark after the type, like int?. This tells C# to allow that variable to hold either an integer or no value.

💻

Example

This example shows how to declare a nullable integer, check if it has a value, and print the value or a message if it is null.

csharp
int? age = null;
if (age.HasValue)
{
    Console.WriteLine($"Age is {age.Value}");
}
else
{
    Console.WriteLine("Age is not set");
}

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

When to Use

Use nullable structs when you need to represent the absence of a value for value types. This is common in databases where a field might be empty, or in user input where a number might not be provided.

For example, if you have a form asking for a user's age, but the user can skip it, you can use int? to store the age. This way, you know if the age was given or not.

Nullable structs help avoid errors and make your code clearer by explicitly handling missing values.

Key Points

  • Nullable structs allow value types to hold null as a valid state.
  • Use the ? syntax to declare nullable value types, like int?.
  • Check if a nullable has a value using HasValue or compare to null.
  • Access the actual value with Value property, but only if it has a value.
  • Useful for representing optional data or missing values in value types.

Key Takeaways

Nullable structs let value types hold null to represent no value.
Declare nullable types with a question mark, like int?.
Always check HasValue before accessing the Value property.
Use nullable structs to handle optional or missing data clearly.
They help avoid confusion between default values and missing values.