1

Possible Duplicate:
casting vs using the ‘as’ keyword in the CLR

hi,

can 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.

Community
  • 1
  • 1
Shrewdroid
  • 800
  • 1
  • 10
  • 31

2 Answers2

1

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.

Joel
  • 16,474
  • 17
  • 72
  • 93
  • "as only works with nullable objects, so you can't use as with structs.": Nullables *are* structs. I think you mean you can't use it with non-nullable structs. http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx – Mark Byers May 26 '10 at 05:58
0

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.

Itay Karo
  • 17,924
  • 4
  • 40
  • 58