Question

If I have a nullable "decimal? d" and I want to assign d to non nullable e, what is the proper way?

Was it helpful?

Solution

decimal e = d ?? 0.0;

OTHER TIPS

decimal e;
if(d.HasValue) 
{
    e = d.Value;
}

You need to determine whether you even can, i.e. whether the nullable d has a value or not.

if (d.HasValue) { e = d.Value; } else { /* now what */ }

Another interesting case comes up quite commonly where you want to assign to a nullable using a ternary, in which case you have to cast to make both branches have the same type.

d = foo ? 45 : (int?)null;

Note the case of null to (int?) so that both branches have the same type.

decimal e;

if (d.HasValue)
{
    e = d.Value;
}

I usually go with something like this:

decimal e = d.HasValue ? d.Value : decimal.Zero;

The reason here is that I'm a fan of ternary operations and I usually assign the value I would get if I had perfermed a failed TryParse() for the type I am dealing with. For decimal that would be decimal.Zero, for int it would be 0 as well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top