In C#, how do I specify OR:
if(this OR that) {do the other thing}
I couldn\'t find it in the help.
Update:
The conditional or operator is ||:
if (expr1 || expr2) {do stuff}
if (title == "User greeting" || title == "User name") {do stuff}
The conditional (the OR) and it's parts are boolean expressions.
MSDN lists the C# operators in precedence order here http://msdn.microsoft.com/en-us/library/6a71f45d.aspx . And the MSDN page for boolean expressions is http://msdn.microsoft.com/en-us/library/dya2szfk.aspx .
If you are just starting to learn programming, you should read up on Conditional Statements from an introductory text or tutorial. This one seems to cover most of the basics: http://www.functionx.com/csharp/Lesson10.htm .
The OR operator is a double pipe:
||
So it looks like:
if (this || that)
{
//do the other thing
}
EDIT: The reason that your updated attempt isn't working is because the logical operators must separate valid C# expressions. Expressions have operands and operators and operators have an order of precedence.
In your case, the == operator is evaluated first. This means your expression is being evaluated as (title == "User greeting") || "User name"
. The || gets evaluated next. Since || requires each operand to be a boolean expression, it fails, because your operands are strings.
Using two separate boolean expressions will ensure that your ||
operator will work properly.
title == "User greeting" || title == "User name"
Or is ||
And is &&
Update for changed question:
You need to specify what you are comparing against in each logical section of the if statement.
if (title == "User greeting" || title == "User name")
{
// do stuff
}
In the format for if
if (this OR that)
this
and that
are expression not values. title == "aaaaa"
is a valid expression. Also OR
is not a valid construct in C#, you have to use ||
.
Just for completeness, the || and && are the conditional version of the | and & operators.
A reference to the ECMA C# Language specification is here.
From the specification:
3 The operation x || y corresponds to the operation x | y, except that y is evaluated only if x is false.
In the |
version both sides are evaluated.
The conditional version short circuits evaluation and so allows for code like:
if (x == null || x.Value == 5)
// Do something
Or (no pun intended) using your example:
if (title == "User greeting" || title == "User name")
// {do stuff}
you need
if (title == "User greeting" || title == "User name") {do stuff};