Last Update: Jan 5, 2023

The average C# Developer makes $134,270 per year.
This set of C# courses will help you get there! 38 hours from beginner to expert.


I just had this problem tonight, so I thought I’d share the solution. In many languages you can just drop in a string and compare it like this:

if ($city == "Portland" || $city == "Seattle")
{
  // do something if city is Portland or Seattle
}else
{
  // do something else
}

And this works just fine. But in C#, strings are treated as objects, so you have to do the same comparison as such:

if ((city == "Portland") || (city == "Seattle"))
{
  // do something if city is Portland or Seattle
}else {
  // do something else
}

You have to put the parenthesis around it.

In the above example, if the city is Portland, it will evaluate as true, making it a boolean. This is a simple step and an easy fix, but I couldn’t readily find anything on google about it, so I thought I’d post it here.

How Do OR operators work in C#?

In C#, the || operator is used to perform a logical OR operation. It tests whether at least one of two expressions is true. If either expression is true, the result of the OR operation is true. If both expressions are false, the result is false. Here is an example of how to use the OR operator in C#:

bool value1 = true;
bool value2 = false;

if (value1 || value2)
{
    // one or both of these values is true
}

You can also use the | operator to do a bitwise OR operation in C#.

The | operator compares each bit of the first operand to the corresponding bit of the second operand. If either bit is 1, the corresponding result bit is set to 1. If not, the corresponding result bit is set to 0.

Here is an example of how to use the bitwise OR operator in C#:

int value1 = 3; // Binary: 011
int value2 = 7; // Binary: 111
int value3 = value1 | value2; // Binary: 111 = 7

Console.WriteLine(value2); // Outputs 7

And with this code you can do bitwise OR operations in C#!

Questions? Comments? Discuss it here



Join the .NET Wizards Newsletter!

Keep up with the latest news and trends with .NET devlopment

* indicates required


Published: Dec 8, 2008 by Jeremy Morgan. Contact me before republishing this content.