Introduction
Here we will discuss how to overload short-circuit operators in C#. This articles assumes knowledge of operator overloading in C#.
The short-circuit operators are && and ||. They work nearly the same as ampersand (&) and simple pipeline (|) but there are some differences how the short-circuit operators work and the ampersand single pipeline.
bool a=false;
bool b = true;
If(a & b)
//some code
If(a && b)
//some code
For a layman, both expressions will work the same and will generate the same output but for experienced programmers there is a difference between how the short-circuit (&&) and ampersand (&) work.
How a short-circuit works
In C# a short-circuit operator can used in a bool expression only . it will return true and depending on the condition in the control statement.
If the short-circuit finda an operand that can reflect the result of the expression then it will stop checking the remaining operands and execute the condition true or false that is being reflected by the operand.
In the code above in the if statement && will find that a is false and in the AND operator all the operands must be true in order to execute if the statement. In this case a is false so it will not check b and will transfer control to the else statement. The && and || operators do not work with integers or any other type except bool.
Working of ampersand or single pipeline operator
The main difference between a short-circuit and a single pipeline/ampersand operator is the & and | operators can work with integers too. It compares the two operands bitwise and ANDs them. The result can be stores in another integer variable as in the following:
int a =4&5// this will compare 4 and 5 bitwise and AND them in binary form
int b=4|5// this compare 4and 5 bitwise and OR them in binary form
Another difference is that the & and| operator check all the conditions, even if the result of the control statement is being reflected by the current operand.
bool a=false;
bool b = true;
If(a & b) // result of b will also be check event a reflect that the statement is false
//some code
If(b|a)// b reflect result of statement but it will still check a
//some code
Overloading short-circuit operator
C# did not allow overloading the short-circuit operator directly just like +,-,/,|,& and so on.
But there are certain rules if we fulfil them when can use a short-circuit operator for a user-defined data type or in a simple that can overload them. In fact we do not overload them but if the conditions are fulfilled then they are overloaded by the compiler logically.
Rules for overloading the short-circuit operator.
Join the conversation! Your thoughts help the community grow.
Sign in to leave a comment
It is the same account you read, post and publish with — and you will come straight back to this page.


Dinesh BeniwalPosted Jul 8, 2014, 2:44 AM
Good start Simi, Welcome to the C# Corner.