Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a reason to cast to a type then to its nullable type?

So I just saw this line of code:

Item = (int?)(int)row["Item"];

Is there a reason it cant just be:

Item = (int?)row["Item"];
like image 340
RJP Avatar asked Oct 11 '12 18:10

RJP


2 Answers

See Boxing Nullable Types (C#); an object can be directly cast to a nullable int (but it will cause an InvalidCastException if the object isn't actually an int). The one thing that the two casts will do that a direct cast to int? will not is perform an implicit check for null.

When casting to an int and then to a nullable int, an ICE will be thrown if the value of the object variable is null. When casting directly to a nullable int, null is handled just fine, but an InvalidOperationException will be thrown if code then attempts to retrieve the Value property without checking that there actually is one.

This looks like a half-assed attempt to "fail fast", and I would not recommend it as "good code". Simply cast directly to nullable, and then test the HasValue property and go from there.

like image 172
KeithS Avatar answered Nov 15 '22 08:11

KeithS


I believe the proper way to write this line of code is this:

int val;
var success = int.TryParse(Convert.ToString(row["Item"]), out val);
Item = success ? (int?)val : (int?)null;
like image 39
Mike Perrenoud Avatar answered Nov 15 '22 10:11

Mike Perrenoud