开发者

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.


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.)


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';


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.


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


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 ;)


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

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


Or is || in C#.

You may have a look at this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜