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?