Programming Blog

Jeremy Morgan

Mostly Coherent Ramblings of a Silicon Forest Software Developer

How to Use or Operator With Strings in C#

Author: Jeremy Morgan

I just had this problem tonight, so I thought I’d share the solution. In many languages you can do a string comparison in the following way:

if ($city == "Portland" || $city == "Seattle") {
// stuff goes here

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")) {
// stuff goes here

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.

If you want to use the || or operator in C#, this is how you do it.

Do you like articles like this?

I’m constantly hacking on stuff and writing about happenings in the programmer world. You can subscribe to my feed here, or you can get the hacker newsletter 100% spam free!

You can also follow my projects on GitHub: