in ,

Programming: How one can use OR operator with Strings in C#


Final Replace: Jan 5, 2023


I simply had this downside tonight, so I assumed I’d share the answer. In lots of languages you possibly can simply drop in a string and evaluate it like this:

if ($metropolis == "Portland" || $metropolis == "Seattle")
{
  // do one thing if metropolis is Portland or Seattle
}else
{
  // do one thing else
}

And this works simply effective. However in C#, strings are handled as objects, so you must do the identical comparability as such:

if ((metropolis == "Portland") || (metropolis == "Seattle"))
{
  // do one thing if metropolis is Portland or Seattle
}else {
  // do one thing else
}

You must put the parenthesis round it.

Within the above instance, if the town is Portland, it’s going to consider as true, making it a boolean. It is a easy step and a simple repair, however I couldn’t readily discover something on google about it, so I assumed I’d publish it right here.

How Do OR operators work in C#?

In C#, the || operator is used to carry out a logical OR operation.
It assessments whether or not at the least one in all two expressions is true. If both expression is true, the results of the OR operation is true. If each expressions are false, the result’s false. Right here is an instance of tips on how to use the OR operator in C#:

bool value1 = true;
bool value2 = false;

if (value1 || value2)
{
    // one or each of those values is true
}

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

The | operator compares every little bit of the primary operand to the corresponding little bit of the second operand. If both bit is 1, the corresponding consequence bit is about to 1. If not, the corresponding consequence bit is about to 0.

Right here is an instance of tips on 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 are able to do bitwise OR operations in C#!





Supply hyperlink

What do you think?

Written by admin

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *

GIPHY App Key not set. Please check settings

Bitvae Water Flosser with 6 Attachments for simply $18.99 with free Prime delivery!

Google Picture & Video Search Testing Blurring Express Content material, As a substitute Of Eradicating It