Jarred Sumner
Jarred Sumner

Reputation: 1853

C# 'or' operator?

Is there an or operator in C#?

I want to do:

if (ActionsLogWriter.Close or ErrorDumpWriter.Close == true)
{
    // Do stuff here
}

But I'm not sure how I could do something like that.

Upvotes: 34

Views: 259488

Answers (7)

Noah Stahl
Noah Stahl

Reputation: 7553

As of C# 9, there is an or keyword that can be used in matching a "disjunctive pattern". This is part of several new pattern matching enhancements in this version.

An example from the docs:

public static bool IsLetter(this char c) => c is >= 'a' and <= 'z' or >= 'A' and <= 'Z';

Upvotes: 25

wls223
wls223

Reputation: 31

The single " | " operator will evaluate both sides of the expression.

    if (ActionsLogWriter.Close | ErrorDumpWriter.Close == true)
{
    // Do stuff here
}

The double operator " || " will only evaluate the left side if the expression returns true.

    if (ActionsLogWriter.Close || ErrorDumpWriter.Close == true)
{
    // Do stuff here
}

C# has many similarities to C++ but their still are differences between the two languages ;)

Upvotes: 3

Jeff Sternal
Jeff Sternal

Reputation: 48583

C# supports two boolean or operators: the single bar | and the double-bar ||.

The difference is that | always checks both the left and right conditions, while || only checks the right-side condition if it's necessary (if the left side evaluates to false).

This is significant when the condition on the right-side involves processing or results in side effects. (For example, if your ErrorDumpWriter.Close method took a while to complete or changed something's state.)

Upvotes: 101

Josh
Josh

Reputation: 69252

Also worth mentioning, in C# the OR operator is short-circuiting. In your example, Close seems to be a property, but if it were a method, it's worth noting that:

if (ActionsLogWriter.Close() || ErrorDumpWriter.Close())

is fundamentally different from

if (ErrorDumpWriter.Close() || ActionsLogWriter.Close())

In C#, if the first expression returns true, the second expression will not be evaluated at all. Just be aware of this. It actually works to your advantage most of the time.

Upvotes: 9

Secko
Secko

Reputation: 7716

Or is || in C#.

You may have a look at this.

Upvotes: 2

Jeff Paquette
Jeff Paquette

Reputation: 7127

just like in C and C++, the boolean or operator is ||

if (ActionsLogWriter.Close || ErrorDumpWriter.Close == true)
{
    // Do stuff here
}

Upvotes: 2

Dave Barker
Dave Barker

Reputation: 6437

if (ActionsLogWriter.Close || ErrorDumpWriter.Close == true)
{    // Do stuff here
}

Upvotes: 4

Related Questions