If you know that v1
has a value, you can use the Value
property:
v2 = v1.Value;
Using the GetValueOrDefault
method will assign the value if there is one, otherwise the default for the type, or a default value that you specify:
v2 = v1.GetValueOrDefault(); // assigns zero if v1 has no value
v2 = v1.GetValueOrDefault(-1); // assigns -1 if v1 has no value
You can use the HasValue
property to check if v1
has a value:
if (v1.HasValue) {
v2 = v1.Value;
}
There is also language support for the GetValueOrDefault(T)
method:
v2 = v1 ?? -1;