C#
C#

help

Root Question Message

Groophy
Groophy2/11/2023
✅ Simple question

I have a code which
if ("any" is "item1" or "item2" or "any")
{
    Console.WriteLine("okay");
}

that prints okay but out of curiosity, can I do this with symbols? like
if ("any" == "item1" || "item2" || "any") // "any" == "item1" || "any" == "item2" will be corrent but really bad readable
{
    Console.WriteLine("okay");
}
Ero
Ero2/11/2023
Well, can you do it?
Ero
Ero2/11/2023
Have you tried? Did it work?
JansthcirlU
JansthcirlU2/11/2023
The first code block is using pattern matching, it's a specific feature where you can use or to test against for different matches. The second code block uses the binary conditional logic operators which only work on booleans (true or false).
TheBoxyBear
TheBoxyBear2/11/2023
Only works with bools and it so happens the logical and equality operators return bool. Pattern matching helps make it more readable and can warn you if the expression is contradictory or will always be true. As a side effect, pattern matching only works when comparing to constants.
cumslvt13
cumslvt132/11/2023
The code you've shown compiles into plain ||'s. Take a look at sharplab decompile:

internal class Program
{
    private static void <Main>$(string[] args)
    {
        string text = "any";
        if (text == "item1" || text == "item2" || text == "any")
        {
            Console.WriteLine("okay");
        }
    }
}


https://sharplab.io/#v2:CYLg1APgAgTADAWAFCwIzOQNwIYCcAE2+AvPgETYB2AnmQNwZICWAZvgBRFMDO5TALgFMAtqjL4A9gTICRMcVPJVaASmQBvZPm34oqAJzsyEgNbZVDJAF8gA
Groophy
Groophy2/11/2023
Thanks for best explain.
Groophy
Groophy2/11/2023
$close
ContactFrequently Asked QuestionsJoin The DiscordBugs & Feature RequestsTerms & Privacy