How to Use HasValue and Value in Nullable Types in C#
In C#,
HasValue checks if a nullable variable contains a value, returning true if it does and false if it is null. The Value property retrieves the actual value but should only be used after confirming HasValue is true to avoid exceptions.Syntax
A nullable type in C# is declared by adding ? after a value type, like int?. The HasValue property returns true if the variable holds a value, otherwise false. The Value property returns the stored value but throws an exception if the variable is null.
csharp
int? number = 5; bool hasValue = number.HasValue; // true int value = number.Value; // 5
Example
This example shows how to safely check if a nullable integer has a value before accessing it to avoid runtime errors.
csharp
using System; class Program { static void Main() { int? nullableNumber = null; if (nullableNumber.HasValue) { Console.WriteLine($"Value is: {nullableNumber.Value}"); } else { Console.WriteLine("No value assigned (null)."); } nullableNumber = 42; if (nullableNumber.HasValue) { Console.WriteLine($"Value is: {nullableNumber.Value}"); } } }
Output
No value assigned (null).
Value is: 42
Common Pitfalls
Trying to access Value without checking HasValue causes an InvalidOperationException. Always check HasValue before using Value or use the null-coalescing operator ?? as a safer alternative.
csharp
int? number = null; // Wrong: throws exception // int value = number.Value; // Right: check HasValue first if (number.HasValue) { int value = number.Value; Console.WriteLine(value); } else { Console.WriteLine("No value to access."); } // Alternative safe way int safeValue = number ?? 0; // uses 0 if null Console.WriteLine(safeValue);
Output
No value to access.
0
Quick Reference
| Property | Description | Example Usage |
|---|---|---|
| HasValue | Returns true if nullable has a value | if (nullable.HasValue) { ... } |
| Value | Gets the value if present; throws if null | int val = nullable.Value; |
| Null-coalescing (??) | Provides default if null | int val = nullable ?? 0; |
Key Takeaways
Always check
HasValue before accessing Value to avoid exceptions.Use nullable types with
? to represent optional values.The
Value property throws an exception if the nullable is null.Use the null-coalescing operator
?? for safer default values.Checking
HasValue helps write clear and safe code when working with nullable types.