I am currently facing the following problem with a Menu Strip
containing several different settings such as:
- Show X
- Show Y
- Show Z
All those items have corresponding properties of the type bool
, because those variables are also passed to other classes. Currently, when I click on "Show Y", I have a dedicated function called HandleShowY()
which toggles the bool
and the checkmark within the Menu Strip Item.
A new method for every newly added property seems like a huge code smell to me and requires a ton of added overhead for each new property. Thus, I came up with the idea to make a generic HandleMenuStripItemBool()
which receives the property and the menu item by reference, such that only one method exists to handle this type of behaviour.
Unfortunately, I am running into problems while trying to pass my bool
property to this method by reference, my knowledge of action
, func
and delegate
has mostly faded away and only confuses me more and more after every new tutorial I read.
Example code:
// different properties of type bool, defined in form1
private bool ShowX { get; set; }
private bool ShowY { get; set; }
// generic menu strip item bool handler
private void HandleMenuStripItemBool(bool boolProp, ToolStripMenuItem menuItem)
{
// toggle bool depending on current value
// add check mark to or remove check mark from ToolStripMenuItem
}
// click event of the "Show X" menu strip item, defined in form1
private void showXToolStripMenuItem_Click(object sender, EventArgs e)
{
HandleMenuStripItemBool(ShowX, showXToolStripMenuItem);
}
// click event of the "Show Y" menu strip item, defined in form1
private void showYToolStripMenuItem_Click(object sender, EventArgs e)
{
HandleMenuStripItemBool(ShowY, showYToolStripMenuItem);
}
TL;DR: what is the best way to create a method which receives a property of the type bool
by reference, in such a way that the method can be reused for several other properties?
Thanks in advance.