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"];
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With