Reputation: 93434
I have always gone by the idea that casting should be avoided at all costs. Of course, there are times you have no real choice (particularly when you need to cast between interface types when multiple interfaces are supported).
One pattern i've seen myself using a lot lately is casting from a non-nullable type to nullable type. For example:
public int? GetFooBar(someCriteria) {
// Code to get a Foo
return foo == null ? null : (int?)foo.Bar; // Bar is a non-null int
}
Is they cast my only choice here? What other options might I have?
I suppose i could just throw an exception, but I don't like litering my code with exception handlers that aren't necessary. Plus, not finding a foo might be an expected occurance, and not considered "exceptional".
Upvotes: 0
Views: 182
Reputation: 4992
Let me just point out that
return foo == null ? null : (int?)foo.Bar;
compiles to the same opcodes as
return foo == null ? new Nullable<int>() : new Nullable<int>(foo.Bar);
The version with an if statement might also compile to the same opcodes, so it's really just a matter of personal taste. How about this version:
return foo == null ? (int?)null : foo.Bar;
Same thing. You have to point out the nullable part in either the second or third operand of the conditional operator if you want to use it.
Upvotes: 0
Reputation: 224904
You could always:
if(foo == null)
return null;
return foo.Bar;
No casting involved and a little clearer, at the expense of conciseness.
Upvotes: 4