To answer your actual question: Experience and habit.
Before the inclusion of the as
keyword in .Net 2.0, the only way to safely determine if an object could be cast to a specific type/interface was with the is
keyword.
So, people got in the habit of using is
before attempting an explicit cast in order to avoid unnecessary exceptions. This led to the pattern you have second in your list of samples:
if(whatever is IDisposable) //check
{
((IDisposable)whatever).Dispose(); //cast - won't fail
}
Then, we got the safe-cast as
keyword. I would guess that most people, when they first started using as
, continued to use the familiar pattern, but replaced the direct cast with a safe-cast, and their pattern of choice morphed into your example 1. (I know I did this for awhile.)
if(whatever is IDisposable)
{
(whatever as IDisposable).Dispose();
}
Eventually, many or most either realized on their own, or were instructed by fxCop or CodeAnalysis that the 'proper' pattern is your example 3:
IDisposable whateverDisposable = whatever as IDisposable;
if(whateverDisposable != null )
{
whateverDisposable.Dispose();
}
Certainly there are some floating around who are at the example 1 stage still and haven't yet 'evolved' their pattern to your example 3 for some reason, or others who are still just using the good-old time-proven pattern of using is
followed by a direct cast.