Object Casting in C#
The first is an explicit cast, and the second is a conversion. If the conversion fails for the as
keyword, it will simply return null
instead of throwing an exception.
This is the documentation for each:
- Casting and Type Conversions (C# Programming Guide)
- as (C# Reference)
Note in the linked documentation above, they state the as
keyword does not support user-defined conversions. +1 to Zxpro :) This is what a user-defined conversion is:
User-Defined Conversions Tutorial
My usual guidance on using the as
operator versus a direct cast are as follows:
- If the cast must succeed (i.e. it would be an error to continue if the cast failed), use a direct cast.
- If the cast might fail and there needs to be programmatic detection of this, use the
as
operator.
The above is true for reference types. For value types (like bool
or int
), as
does not work. In that case, you will need to use an is
check to do a "safe cast", like this:
if (x is int y)
{
// y is now a int, with the correct value
}
else
{
// ...
}
I do not recommend trying to catch InvalidCastException
, as this is generally the sign of a programmer error. Use the guidance above instead.
I believe that casting using the first method throws an exception if it can't cast the object properly (trying to cast the wrong type), whereas using the as keyword will simply set the variable to null if it couldn't cast it properly.
So make sure that if you use the as keyword cast, you check
if(lb == null)
return null; // or throw new Exception()
and if you use the () cast, you surround it with
try
{
LinkButton lb = (LinkButton)ctl;
}
catch(InvalidCastException ex)
{
//TODO: Handle Exception
}