What is the OR operator in an IF statement

前端 未结 11 776
轮回少年
轮回少年 2020-12-14 05:50

In C#, how do I specify OR:

if(this OR that) {do the other thing}

I couldn\'t find it in the help.

Update:

相关标签:
11条回答
  • 2020-12-14 06:45

    hopefully you would have got an idea by now.if intrested you can also have a look at the c# specification at http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf

    0 讨论(0)
  • 2020-12-14 06:49

    OR is used as "||"

     if(expr1 || expr2)
     {
        do something
     }
    
    0 讨论(0)
  • 2020-12-14 06:50

    The reason this is wrong:

    if (title == "User greeting" || "User name") {do stuff};
    

    is because what that's saying is

    If title equals the string "User greeting"

    or just "User name" (not if title equals the string "User name"). The part after your or would be like writing

    if ("User name")
    

    which c# doesn't know what to do with. It can't figure out how to get a boolean out of "User name"

    0 讨论(0)
  • 2020-12-14 06:51

    || is the conditional OR operator in C#

    You probably had a hard time finding it because it's difficult to search for something whose name you don't know. Next time try doing a Google search for "C# Operators" and look at the logical operators.

    Here is a list of C# operators.

    My code is:

    if (title == "User greeting" || "User name") {do stuff};
    

    and my error is:

    Error 1 Operator '||' cannot be applied to operands of type 'bool' and 'string' C:\Documents and Settings\Sky View Barns\My Documents\Visual Studio 2005\Projects\FOL Ministry\FOL Ministry\Downloader.cs 63 21 FOL Ministry

    You need to do this instead:

    if (title == "User greeting" || title == "User name") {do stuff};
    

    The OR operator evaluates the expressions on both sides the same way. In your example, you are operating on the expression title == "User greeting" (a bool) and the expression "User name" (a string). These can't be combined directly without a cast or conversion, which is why you're getting the error.

    In addition, it is worth noting that the || operator uses "short-circuit evaluation". This means that if the first expression evaluates to true, the second expression is not evaluated because it doesn't have to be - the end result will always be true. Sometimes you can take advantage of this during optimization.

    One last quick note - I often write my conditionals with nested parentheses like this:

    if ((title == "User greeting") || (title == "User name")) {do stuff};
    

    This way I can control precedence and don't have to worry about the order of operations. It's probably overkill here, but it's especially useful when the logic gets complicated.

    0 讨论(0)
  • 2020-12-14 06:54

    See C# Operators for C# operators including OR which is ||

    0 讨论(0)
提交回复
热议问题