tags:

views:

538

answers:

5

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

+1  A: 
decimal e;

if (d.HasValue)
{
    e = d.Value;
}
Mike C.
and what value should e take when d is null?
Sebastian Good
I could say -1 for possible 'System.InvalidOperationException' but i wont.
Phaedrus
This answer is right now, but only after copying Phaedrus' answer.
Graphain
Jeez, don't get so testy Graphain. I fixed my invalid code. And nice catch, Phaedrus. I rushed my answer.
Mike C.
And technically, I didn't copy the answer.
Mike C.
+2  A: 

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.

Sebastian Good
Good point on the ternary operator thing. Always kind of annoyed me I have to cast null to a type here :-)
Graphain
+9  A: 
decimal e;
if(d.HasValue) 
{
    e = d.Value;
}
Phaedrus
-1 for declaring a variable that will go out of scope after you assign to it.
Mike C.
Good catch, but his principle is right.
Graphain
That's not a reason to downvote. It answers the question, and if someone doesn't know that e needs to be declared outside an if block, they have bigger problems than Nullable types.
BFree
(You'd notice his error quickly, you wouldn't notice possible System.InvalidOperationExceptions as quickly).
Graphain
Edited to move 'decimal e;' declaration outside the scope (all correct now).
Graphain
-1 removed after code was fixed.
Mike C.
+12  A: 
decimal e = d ?? 0.0;
Ralph
Love the null coalescing operator. This expands to 'decimal e = d != null ? d : 0.0;'
Graphain
Exactly, to me this is short and sweet and allows you to treat the nullable type succinctly. You don't have to worry about using the .HasValue or .Value properties either.
Ralph
Echoing other comments - this is the way to do it.
Chuck
A: 

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.

Alexander Kahoun