Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# 'or' operator?

Tags:

c#

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.

like image 725
Jarred Sumner Avatar asked Nov 17 '09 02:11

Jarred Sumner


2 Answers

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

like image 52
Jeff Sternal Avatar answered Sep 21 '22 00:09

Jeff Sternal


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.

like image 20
Josh Avatar answered Sep 18 '22 00:09

Josh