user279521
user279521

Reputation: 4807

Understanding syntax in C#

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?

Upvotes: 1

Views: 301

Answers (4)

Sunny
Sunny

Reputation: 6346

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;
  }

}

Upvotes: 1

Mikael Svenson
Mikael Svenson

Reputation: 39695

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.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500495

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

Upvotes: 10

Related Questions