Get the value of a nullable type
suggest changeGiven the following nullable int:
int? i = 10;
When a fallback value is needed, use the null-coalescing operator, GetValueOrDefault, or a HasValue check. Each line below is a separate alternative:
int j = i ?? 0;
int j = i.GetValueOrDefault(0);
int j = i.HasValue ? i.Value : 0;
Reading .Value when the nullable has no value throws InvalidOperationException. A local int? that was never assigned is a compile-time error instead (Use of unassigned local variable).
int j = i.Value;
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents