C
C#3y ago
Kamil Pisz

Switch order when two cases meet condition, How precedence work here?

switch (name)
{
case string a when a.Contains("John Dee"):
DoSomething1;
break;
case string a when a.Contains("John"):
DoSomething1;
break;
case string a when a.Equeals("John Dee"): //equals
DoSomething1;
break;
}
switch (name)
{
case string a when a.Contains("John Dee"):
DoSomething1;
break;
case string a when a.Contains("John"):
DoSomething1;
break;
case string a when a.Equeals("John Dee"): //equals
DoSomething1;
break;
}
IF name = "John Dee" which one case hit first ?
2 Replies
Cracker
Cracker3y ago
Starts checking the cases from up to bottom. Whenever case matches, it goes inside the case, if you used break; then it wont go further down to check other cases If you don't use break; then it will still check for other cases You can easily debug the behavior In you example first case will be hit and DoSomething1 is executed then switch statement breaked, meaning no more case check further below
vdvman1
vdvman13y ago
C# doesn't let you fallthrough to the next case by leaving out the break But yes, it checks in order from top to bottom
Want results from more Discord servers?
Add your server