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?
My rules of thumb around casting:
as, like in your second caseaswith the nullable type (for consistency) or useisand 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.