If I have a nullable "decimal? d" and I want to assign d to non nullable e, what is the proper way?
and what value should e take when d is null?
Sebastian Good
2009-05-01 03:06:42
I could say -1 for possible 'System.InvalidOperationException' but i wont.
Phaedrus
2009-05-01 03:09:29
This answer is right now, but only after copying Phaedrus' answer.
Graphain
2009-05-01 03:13:29
Jeez, don't get so testy Graphain. I fixed my invalid code. And nice catch, Phaedrus. I rushed my answer.
Mike C.
2009-05-01 03:17:08
And technically, I didn't copy the answer.
Mike C.
2009-05-01 03:20:48
+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
2009-05-01 03:03:59
Good point on the ternary operator thing. Always kind of annoyed me I have to cast null to a type here :-)
Graphain
2009-05-01 03:16:47
-1 for declaring a variable that will go out of scope after you assign to it.
Mike C.
2009-05-01 03:06:53
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
2009-05-01 03:14:39
(You'd notice his error quickly, you wouldn't notice possible System.InvalidOperationExceptions as quickly).
Graphain
2009-05-01 03:14:45
Edited to move 'decimal e;' declaration outside the scope (all correct now).
Graphain
2009-05-01 03:16:11
Love the null coalescing operator. This expands to 'decimal e = d != null ? d : 0.0;'
Graphain
2009-05-01 03:18:03
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
2009-05-01 03:21:10
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
2009-05-01 03:20:14