What is Nullable Type in C#: Explanation and Examples
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.
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}"); } } }
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
.HasValueto check if there is a value. - Use
.Valueto get the actual value safely after checking. - They help represent missing or optional data clearly.