C
C#2y ago
Groophy

✅ Simple question

I have a code which
if ("any" is "item1" or "item2" or "any")
{
Console.WriteLine("okay");
}
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");
}
if ("any" == "item1" || "item2" || "any") // "any" == "item1" || "any" == "item2" will be corrent but really bad readable
{
Console.WriteLine("okay");
}
6 Replies
ero
ero2y ago
Well, can you do it? Have you tried? Did it work?
JansthcirlU
JansthcirlU2y ago
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
TheBoxyBear2y ago
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
cumslvt132y ago
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");
}
}
}
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
SharpLab
C#/VB/F# compiler playground.
Groophy
Groophy2y ago
Thanks for best explain. $close
MODiX
MODiX2y ago
Use the /close command to mark a forum thread as answered