I would have liked to do something like
switch(true) {
case box1.Checked:
do_something(); break;
case box2.Checked:
do_something_else();
and_some_more(); break;
default:
complain_loudly();
}
But that is not allowed in c#; it is in php.
Is there a neater way, besides a
if (box1.Checked) {
do_something();
} else if (box2.checked)
...
?
With C# 7 using case with when. See also The case statement and the when clause
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Box box1 = new Box();
Box box2 = new Box();
box2.Checked = true;
switch (true)
{
case true when box1.Checked:
Console.WriteLine("box1 is checked");
break;
case true when box2.Checked:
Console.WriteLine("box2 is checked");
break;
default:
Console.WriteLine("neither box checked");
break;
}
return;
}
}
class Box
{
public bool Checked = false;
}
}
Output:
box2 is checked
I would try something like this - find fist checked checkbox from collection and then switch-case by name of checked control... Something like this:
var checkedCb = this.Controls.OfType<CheckBox>().Where(c => c.Checked).First();
switch (checkedCb.Name)
{
case "cbOne":
break;
case "cbTwo":
break;
default:
break;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With