Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Anonymous variable in when expression of switch statements

I want to deal with multi condition with switch. Here is my code:

string i="a1";
switch (i)
{
    case string X when X.Contains("a", StringComparison.OrdinalIgnoreCase):
    case string Y when Y.Contains("b", StringComparison.OrdinalIgnoreCase):
    case string Z when Z.Contains("c", StringComparison.OrdinalIgnoreCase):
    case string A when A.Contains("d", StringComparison.OrdinalIgnoreCase):
        {
            //some logic
            break;
        }
    case string X when X.Contains("e", StringComparison.Ordinal):
        {
            //some logic     
            break;
        }                               
}

As you see, the variable X/Y/Z/A in the switch statement is useless for me while I have to declare them every time.

Is there any way I can achieve it without declaring so many useless variables?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use a type matching pattern without introducing a new pattern variable, and then refer to i in the guard clause:

string i = "a1";
switch (i)
{
    case string when i.Contains("a", StringComparison.OrdinalIgnoreCase):
    case string when i.Contains("b", StringComparison.OrdinalIgnoreCase):
    case string when i.Contains("c", StringComparison.OrdinalIgnoreCase):
    case string when i.Contains("d", StringComparison.OrdinalIgnoreCase):
    {
        // some logic
        break;
    }
    case string when i.Contains("e", StringComparison.Ordinal):
    {
        // some logic     
        break;
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading