0

I want to use switch like if in my code but I dont know how to use && in case ! this is my code

string a;
a = System.Convert.ToString(textBox1.Text);

if (a.Contains('h') && a.Contains('s'))
{
    this.BackColor=Color.Red;
}
else if (a.Contains('r') && a.Contains('z')) 
{
    this.BackColor=Color.Black;

}

else if (a.Contains('a') && a.Contains('b'))
{
    this.BackColor = Color.Pink;

}
5
  • 1
    By the way, textBox1.Text is already a string. Don't bother calling Convert.ToString() on it. There's no need. Commented Oct 26, 2017 at 19:28
  • 3
    Psst, @ed, You can do it with pattern matching in c# 7 learn.microsoft.com/en-us/dotnet/csharp/whats-new/… Commented Oct 26, 2017 at 19:29
  • I must be confused -- I don't know how pattern matching allows what the OP is looking for. Commented Oct 26, 2017 at 19:30
  • 4
    Sajad, what you've got is reasonably clean, readable code. I don't see any need to change it. Commented Oct 26, 2017 at 19:32
  • 1
    @Will Oh crap. I just saw the when. I thought pattern matching was purely the whole type check they added to switch. Didn't even know you could add when expressions after all these months! Commented Oct 26, 2017 at 19:35

1 Answer 1

5

If you can use the later versions of C# you can write it like this:

switch (st)
{
     case var s when s.Contains("asd") && s.Contains("efg"):
         Console.WriteLine(s);
         break;
     case var s when s.Contains("xyz"):
         break;
     // etc.
}

In your particular situation there is no need to introduce new local variables (s) so the code could be written as

switch(st)
{
     case var _ when st.Contains("asd") && st.Contains("efg"):
         Console.WriteLine(st);
         break;
     case var _ when st.Contains("xyz"):
         break;
     // etc.
}

You can read about it on MSDN.

Sign up to request clarification or add additional context in comments.

5 Comments

+1 because whoa, cool -- but I think this isn't a better argument in favor of pattern matching in C# than Duff's Device is in favor of case fall-through in C.
You can avoid the creation of a new variable by using var _
Yeah, variables named _ are always a good confusion sink.</grandpa simpson>
As awesome as this is and does what the OP wants. I still prefer the if statements xD
Actually, when a lot of "when" clauses are added to switch it quickly starts looking even worse than "if-else" chaining. I'll update the answer with "_" syntax in a second (it seems like it's relevant to this particular question)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.