RJP
RJP

Reputation: 4116

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"];

Upvotes: 5

Views: 170

Answers (5)

KeithS
KeithS

Reputation: 71591

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.

Upvotes: 6

dgarbacz
dgarbacz

Reputation: 962

You can actually cast null as the nullable type

Item = sdr.IsDBNull(sdr.GetOrdinal("Item")) ? (int?)null : (int)row["Item"];

Not really sure what exceptions this may cause, but I've used it without issue.

Upvotes: 0

Mike Perrenoud
Mike Perrenoud

Reputation: 67948

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;

Upvotes: 3

Four
Four

Reputation: 900

You can do use the as keyword.

Item = row["Item"] as int?; 

Upvotes: 0

Anton Baksheiev
Anton Baksheiev

Reputation: 2251

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

this line throws exception in case row["Item"] is null. This bad idea, dont do it.

Upvotes: 0

Related Questions