Difference in casting in the following 2 methods [duplicate]
Possible Duplicate:
casting vs using the ‘as’ keyword in the CLR
hi,
ca开发者_如何学运维n somebody please tell me what is the difference between the following two statements, because both of them give me the same results. Also i want to know which is better.
Label lblSome = e.Item.FindControl("lblMyLable") as Label;
&&
Label lblSome = (Label)e.Item.FindControl("lblMyLable");
thank you so much.
as
checks if it can cast it, if it can't, it sets lblSome to null. Normal casting, (Label)
, doesn't do that check for you, just gives you an InvalidCastException
instead. However, as
doesn't work with non-nullable structs.
if e.Item.FindControl("lblMyLable")
returns an object that is not Label (Label)e.Item.FindControl("lblMyLable")
will result in InvalidCastException
.
while e.Item.FindControl("lblMyLable") as Label
will result in null being assigned to lblSome.
精彩评论