Get the value of a nullable type

suggest change

Given 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;

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents