How to Declare Nullable Types in C# Easily
In C#, you declare a nullable type by adding a
? after the value type, like int?. This means the variable can hold a normal value or null. Alternatively, you can use Nullable<T> where T is a value type.Syntax
To declare a nullable type in C#, add a ? after the value type name. This tells the compiler the variable can hold either a value or null.
Example parts:
int?: Nullable integerdouble?: Nullable doubleNullable<int>: Equivalent generic struct form
csharp
int? nullableInt = null; Nullable<double> nullableDouble = 3.14;
Example
This example shows how to declare nullable types, assign values, and check if they have a value or are null.
csharp
using System; class Program { static void Main() { int? age = null; // nullable int with no value double? temperature = 36.6; // nullable double with value if (age.HasValue) Console.WriteLine($"Age: {age.Value}"); else Console.WriteLine("Age is null"); if (temperature != null) Console.WriteLine($"Temperature: {temperature}"); else Console.WriteLine("Temperature is null"); } }
Output
Age is null
Temperature: 36.6
Common Pitfalls
Common mistakes when using nullable types include:
- Trying to assign
nullto a non-nullable value type (e.g.,int x = null;causes error). - Accessing the value without checking if it exists, which throws an exception.
- Confusing nullable reference types (introduced in C# 8) with nullable value types.
Always check HasValue or compare to null before using the value.
csharp
// int x = null; // Error: cannot assign null to int int? y = null; // Correct // Wrong: accessing without check // int value = y.Value; // Throws if y is null // Right: if (y.HasValue) { int value = y.Value; }
Quick Reference
| Concept | Syntax | Description |
|---|---|---|
| Nullable value type | int? | Value type that can hold a value or null |
| Nullable generic struct | Nullable | Equivalent to int? syntax |
| Check if has value | variable.HasValue | Returns true if variable is not null |
| Get value | variable.Value | Gets the value; throws if null |
| Safe access | variable != null | Check before accessing value |
Key Takeaways
Use
? after a value type to declare it nullable, like int?.Always check
HasValue or compare to null before accessing the value.Nullable types allow value types to represent 'no value' safely.
Avoid assigning
null to non-nullable value types to prevent errors.Use
Nullable<T> as an alternative syntax to T?.