In a previous question today these two different approaches was given to a question as answers.
We have an object that might or might not implement IDisposable
. If it does, we want to dispose it, if not we do nothing. The two different approaches are these:
1)
if(toDispose is IDisposable)
(toDispose as IDisposable).Dispose();
2)
IDisposable disposable = toDispose as IDisposable;
if( disposable != null )
disposable.Dispose();
Mainly, from the comments it sounds like the consensus was that 2) was the best approach.
But looking at the differences, we come down to this:
1) Perform a cast twice on toDispose.
2) Only perform the cast once, but create a new intermediate object.
I would guess that 2 will be marginally slower because it has to allocate a new local variable, so why is this regarded as the best solution in this case? It is solely because of readability issues?
Casting and Ranges of Variables. In Java, type casting is used to convert variable values from one type to another. By casting we don't mean something to do with fishing, but it is a similar idea to casting a pot in clay. In Java when you cast you are changing the “shape” (or type) of the variable.
Casting does not create a new object (at least, not unless new conversion operators have been defined, which is uncommon in non-numeric types, and doesn't apply in your example). It merely instructs the compiler how to "treat" an object.
Type casting is when you assign a value of one data type to another type. In C#, there are two types of casting: Implicit Casting (automatically) - converting a smaller type to a larger type size. char -> int -> long -> float -> double. Explicit Casting (manually) - converting a larger type to a smaller size type.
The as operator never throws an exception, and if the conversion is not possible, it will return null. Example: In this example, we only have one cast on each block of code, and also this approach allows you to avoid any exceptions that may occur at execution time.
Not really answering your question but I would recommend you this construct:
using (toDispose as IDisposable)
{
...
}
and let the compiler worry about the ifs
, finally
and Dispose
calls.
My rules of thumb around casting:
as
, like in your second caseas
with the nullable type (for consistency) or use is
and a direct castNote that your second form doesn't create a "new intermediate object". It creates a new intermediate variable. So does your first approach really - it's just that the variable is hidden by the compiler, effectively. It's still present in the IL as a stack location, but it doesn't have any representation in source code.
Having said all of that, in this particular case (where you just want to dispose), Darin's approach is the best one, I believe.
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