Reputation: 832
what is the difference as well as the pros and cons between
LinkButton lb = (LinkButton)ctl;
and
LinkButton lb = ctl as LinkButton;
I tried using the first one and it gives me error, then I tried the other one with the keyword as, it work just fine.
Thank You in Advance.
Upvotes: 13
Views: 30903
Reputation: 24167
My usual guidance on using the as
operator versus a direct cast are as follows:
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.
Upvotes: 9
Reputation: 38367
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:
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
Upvotes: 16
Reputation: 35450
Refer this from @Jon Skeet : What's the difference between cast syntax and using the as operator?
Upvotes: 1
Reputation: 545
The second one is called safe cast, which, instead of throwing exception, will put "null" to your variable. So it does NOT work fine, but sets your LinkButton lb
to null
Upvotes: 2
Reputation: 2045
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
}
Upvotes: 5