Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch on one true expression c#

Tags:

c#

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)
  ...

?

like image 384
Leif Neland Avatar asked Jun 10 '26 02:06

Leif Neland


2 Answers

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
like image 116
Rick Smith Avatar answered Jun 12 '26 16:06

Rick Smith


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;

}
like image 31
Nino Avatar answered Jun 12 '26 15:06

Nino



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!