Get the value of a nullable type

Download c# eBook

Example

Given following nullable int

int? i = 10;

In case default value is needed, you can assign one using null coalescing operator, GetValueOrDefault method or check if nullable int HasValue before assignment.

int j = i ?? 0;
int j = i.GetValueOrDefault(0);
int j = i.HasValue ? i.Value : 0;

The following usage is always unsafe. If i is null at runtime, a System.InvalidOperationException will be thrown. At design time, if a value is not set, you'll get a Use of unassigned local variable 'i' error.

int j = i.Value;

Stats

Contributors: 8
2016-08-01
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook