Last Update: Jan 5, 2023

Coding with AI

I wrote a book! Check out A Quick Guide to Coding with AI.
Become a super programmer!
Learn how to use Generative AI coding tools as a force multiplier for your career.


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




Stay up to date on the latest in Computer Vision and AI.

Get notified when I post new articles!

Intuit Mailchimp




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