Using variables with the As keyword

I have the following code that I am using to hide all Panel controls on a page. However, I would like to be able to modify the HideAllPanels() method so that I can pass it a type and then have it hide all controls of that type.

Everything I try seems to complain when I try to use a variable with with the As keyword. Am I going about this all wrong? Is this even possible?

private void HideAllPanels() { var allControls = FlattenHierachy(Page); foreach (var control in allControls) { var theControl = control as Panel; if (theControl != null) { theControl.Visible = false; } } } private static IEnumerable<Control> FlattenHierachy(Control root) { var list = new List<Control>(); list.Add(root); if (!root.HasControls()) return list.ToArray(); foreach (Control control in root.Controls) { list.AddRange(FlattenHierachy(control)); } return list.ToArray(); } 

by MisplacedSemiColon via /r/csharp

Leave a Reply