views:

179

answers:

4

I am hoping someone can help me understand what is going on in the code line below:

Table t = (Table)Page.FindControl("Panel1").FindControl("tbl");

I understand Page.FindControl("Panel1").FindControl("tbl"); Why is there a (Table) before the Page.FindControl?

+10  A: 

FindControl is declared to return Control (at a guess :) whereas you need to store the result in a variable of type Table.

The (Table) bit is a cast - it's basically saying, "I think this will be a Table. Check it for me at execution time, and then let me use it accordingly."

Jon Skeet
you might also see safe casting by writing it as ...Table t = Page.FindControl("Panel1").FindControl("tbl") as Table;All this does is attempt the cast and if the cast is unsuccessful, say its no longer a table but a textbox now, it'll make t null and won't throw an exception.
jeriley
@jeriley: Yes, although I rarely find this is useful. Normally when I write a cast, it's because if it's any other type, that indicates a bug - so I want an exception to be thrown.
Jon Skeet
I almost never use direct casts in C#. I find `var t = ctl as Table; if (t == null) return fail();` to be much cleaner than `Table t = null; try { t = (Table)ctl; } catch { return fail(); }`.
Mark Booth
@Mark: Why would you catch the exception in the first plcae? Let it propagate up - it indicates a programming error. How are you going to recover from something which shows that things aren't as you expect?
Jon Skeet
@Jon, In my opinion, any cast in C# is an exception waiting to happen. To me it indicates something which is sub-optimal in the design and should probably be factored out at some point. The only time I use casts is when I know that a cast will be significantly more efficient than the alternative and I can satisfy myself that it will never raise an exception.
Mark Booth
+1  A: 

Page.FindControl returns a Control type & so you will need to cast it to the relevant type of control you need to use...

Ref.: http://msdn.microsoft.com/en-us/library/31hxzsdw.aspx

HTH.

Side note:

I wish we could do:

var t = Page.FindControl<Panel>("Panel1").FindControl<Table>("tbl"); 

Maybe with a bit of extension method magic, we could get:

public static class Extension{

  public static T FindControl<T>(this Control control, string id) 
   where T : Control{
       return control.FindControl(id) as T;
  }

}
Sunny
A: 

FindControl returns a type of Control.

Table in your code inherits Control. By explicitly casting the object to it's defined Type, you get access to all properties of that Type, instead of only the inherited properties from Control.

Mikael Svenson
+1  A: 

See () Operator (C# Reference) And Casting and Type Conversions (C# Programming Guide)

ie
Thanks ie. This helps me get deeper into the "when" and "why";
user279521