I am talking in the context of event handler in a C# windows forms, but I'm assuming the answer could be used anywhere in C#.
To give an example, I have a form that has many check boxes that each activate a button. The CheckedChanged event is handled by a function that is very similar for each CheckBox and it looks something like this right now:
private void acheckbox_CheckedChanged(object sender, EventArgs e)
{
int uniquetocheckbox = 12345;
if(acheckbox.CheckedChanged)
{
ThisFunction(uniquetocheckbox, true);
AssociatedButton.Enabled = true;
}
else
{
ThisFunction(uniquetocheckbox, false);
AssociatedButton.Enabled = false;
}
}
There are a lot of these check boxes and I'm trying to cut and past the code for each and make as few changes as possible so I want to do something like this :
private void acheckbox_CheckedChanged(object sender, EventArgs e)
{
int uniquetocheckbox = 12345;
if((CheckBox)sender.Checked) //CHANGE HERE
{
ThisFunction(uniquetocheckbox, true);
AssociatedButton.Enabled = true;
}
else
{
ThisFunction(uniquetocheckbox, false);
AssociatedButton.Enabled = false;
}
}
This does not work. The easy work around is this :
private void acheckbox_CheckedChanged(object sender, EventArgs e)
{
int uniquetocheckbox = 12345;
CheckBox cb = (CheckBox)sender;
if(cb.Checked) //CHANGE HERE
{
ThisFunction(uniquetocheckbox, true);
AssociatedButton.Enabled = true;
}
else
{
ThisFunction(uniquetocheckbox, false);
AssociatedButton.Enabled = false;
}
}
But out of pure curiosity I am wondering if there is a way to do it in one line like the second example I gave. I would like to know because I think it looks better and is obviously 1 line shorter.