Jiminy
Jiminy

Reputation: 605

How do you find out if a control derives from a class

I have a list of controls (_controlList) and from that list of controls I want to get the ones that derive from a given class. So I have code that looks like this.

List<Control> _controlList = new List<Control>();

public Control[] ControlsThatIsA(Type soughtType)
{
  List<Control> result = new List<Control>();
  foreach (Control control in _controlList)
  {
// This would have been nice but doesn't compile
//////////////
//  if (control.GetType() is soughtType)
    {
      result.Add(control);
    }
  }
return result.ToArray();
}

Any thoughts. I don't have to pass in the Type, it could be the string name of the class

Upvotes: 1

Views: 271

Answers (3)

Marc Gravell
Marc Gravell

Reputation: 1062745

First, I'd probably use generics:

public T[] ControlsOfType<T>() where T : Control
{
  List<T> result = new List<T>();
  foreach (Control control in _controlList)
  {
    if (control is T)
    {
      result.Add((T)control);
    }
  }
  return result.ToArray();
}

Or in .NET 3.5:

return _controlList.OfType<T>().ToArray();

If you need to use Type, then IsAssignableFrom is your friend, in particular:

if(soughtType.IsAssignableFrom(control.GetType())) {
   //...
}

Upvotes: 5

pipTheGeek
pipTheGeek

Reputation: 2713

the C# is operator already does a type test (like the Vb TypeOf operator), so it expects something like
if (control is MyNamespace.MyControl)
this is fine if you know the type you are looking for at compile time, but no good for your situation. Also, if your test was changed to do a reference equals test (sorry, I'm a VB programmer really, the VB operator would be IS but I don't know the c# one) then your test would only return true if the control was the type tested for, not it it was inherited from the soughtType.
Try
control.GetType().IsSubClassOf(soughtType)

Note that IsSubClassOf won't return true if control is one of soughtType, but your question did ask to find only controls that inherited from soughtType.

Upvotes: 1

Frederik Gheysels
Frederik Gheysels

Reputation: 56934

if( control is soughtType )
{
}

Upvotes: -1

Related Questions