Search code examples
c#stringif-statementswitch-statementcontains

Use string.Contains() with switch()


I'm doing an C# app where I use

if ((message.Contains("test")))
{
   Console.WriteLine("yes");
} else if ((message.Contains("test2"))) {
   Console.WriteLine("yes for test2");
}

There would be any way to change to switch() the if() statements?


Solution

  • You can do the check at first and then use the switch as you like.

    For example:

    string str = "parameter"; // test1..test2..test3....
    
    if (!message.Contains(str)) return ;
    

    Then

    switch(str)
    {
      case "test1" : {} break;
      case "test2" : {} break;
      default : {} break;
    }