C# - Casting with (T) vs. as (T)18 Sep 2013
In C# there are two methods for casting:
(T)works with both value and reference types. It casts the object to
T, and throws an
InvalidCastExceptionif the cast isn’t valid.
Foo obj = (Foo) bar;
as (T)works only with reference types. It returns the object casted to
Tif it succeeds, and
nullif the cast isn’t valid.
The question therefore is which one should be used where?
(T) means that you fully expect the cast to succeed. If it doesn’t succeed then there is an error in the code that needs looking at.
as (T) on the other hand means that you do not fully expect the cast to succeed in every case. It is considered normal behaviour if the cast did not succeed and this would be taken care of through a null check afterwards.
The only mistake is when you use
as (T) but do not follow it up with a null check. The developer fully expects the cast to succeed so doesn’t write the null check. However later down the line when something goes wrong, no exception is thrown on the invalid cast, no null check is performed, and you have yourself a bug that is hard to track down. It is best to always use the regular cast
(T) unless you intend to check yourself for the invalid cast via
as (T) and a null check afterwards.