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”.
You could always:
No casting involved and a little clearer, at the expense of conciseness.