Is it possible to only use a part of a string in a Switch-Statement?

Viewed 63

savetext is a string with a random length + "! Command1"

switch (savetext)
{
    case savetext.EndsWith("! Command1"):
        System.Diagnostics.Debug.WriteLine("Test1");
        break;

    case savetext.EndsWith("! Command2"):
        System.Diagnostics.Debug.WriteLine("Test2");
        break;

    default:
        System.Diagnostics.Debug.WriteLine(savetext)
        break;
}

The output should be "Test1" but my method here is isnt working like I want. How can I fix this?

2 Answers

Since the suffix you're looking for always has the same length, you could extract it using Substring, and then switch on that:

String switcher = savetext.Substring(savetext.Length - 10);
switch (switcher)
{
    case "! Command1":
        System.Diagnostics.Debug.WriteLine("Test1");
        break;

    case "! Command2":
        System.Diagnostics.Debug.WriteLine("Test2");
        break;

    default:
        System.Diagnostics.Debug.WriteLine(savetext)
        break;
}

A switch statement in C# 8:

var saveText = "111 ! Command1";
var logText = saveText switch
{
    var x when x.EndsWith("! Command1") => "Test 1",
    var x when x.EndsWith("! Command2") => "Test 2",
    var x => x
};

System.Diagnostics.Debug.WriteLine(logText);
Related