3

ToolStripMenuItem and the base type Control both contain the property Enabled.

I need to pass both types to a function such as EnableItems(multipleItems);, but I am not able to find a common base that contain the Enabled property.

Label or LinkLabel inherit from Control (which are typically the types I want to switch from "not enabled" to "enabled").

Is there any way to do this with out of the box features in c#?

Xavier Peña
  • 7,399
  • 9
  • 57
  • 99
  • If your runtime does not support dynamic, it is syntax sugar for reflection See this question, how to set property by name (or get exception :-) ), using reflection http://stackoverflow.com/questions/619767/set-object-property-using-reflection – vitalygolub May 17 '16 at 08:27

2 Answers2

2

Use dynamic type. It allows you to make the compiler trust you. It can give runtime exeptions if you misuse it, but if you are careful there is no problem.

    public static  void Enable(List<object> ctrs, bool enable)
    {
        foreach (var ctr in ctrs)
        {
            dynamic a=ctr;
            a.Enabled = enable;
        }
    }

Pass it a llist with whatever you want to enable or disble. If it have no enable property it will crash at runtime, so be carefull

Aimnox
  • 895
  • 7
  • 20
2

If you didn't want to use a dynamic type then both Control and ToolStripMenuItem inherit from the base class System.ComponentModel.Component. So you could use this as your list type:

public void EnableItems(IList<Component> cpnts)
{
    foreach (Component cpnt in cpnts)
    {
        ToolStripItem tsItem = cpnt as ToolStripItem;
        if (tsItem != null) { tsItem.Enabled = true; break; }

        Control ctrl = cpnt as Control;
        if (ctrl != null) { ctrl.Enabled = true; break; }
    }
}

You can now choose if you want the foreach loop to crash at run time (by adding an exception throw for an unexpected type) or you can choose to ignore the unexpected types.

Ben
  • 3,241
  • 4
  • 35
  • 49