Using .StartsWith in a Switch statement?

Since C# 7 you can do the following:

switch(subArea)
{
    case "4100":
    case "4101":
    case "4102":
    case "4200":
       return "ABC";
    case "600A":
       return "XWZ";
    case string s when s.StartsWith("3*"):
       return "123";
    case string s when s.StartsWith("03*"):
       return "123";
    default:
       return "ABCXYZ123";
}

EDIT: If you are using C# >= 7, take a look at this answer first.


You are switching a String, and subArea.StartsWith() returns a Boolean, that's why you can't do it. I suggest you do it like this:

if (subArea.StartsWith("3*") || subArea.StartsWith("03*"))
    return "123";

switch(subArea)
{
    case "4100":
    case "4101":
    case "4102":
    case "4200":
        return "ABC";
    case "600A":
        return "XWZ";
    default:
        return "ABCXYZ123";
}

The result will be the same.


Thanks to the when clause, you can now do:

switch (subArea)
{
    // Skipping regular cases with string literals
    case string dummy
        when subArea.StartsWith("3*") ||
             subArea.StartsWith("03*"):
        return "123";
    default:
        return "ABCXYZ123";
}

Tags:

C#

.Net

Asp.Net