Click here to Skip to main content
11,486,023 members (75,297 online)
Click here to Skip to main content

Overloading short-circuit operator && and ||

, 6 Jul 2014 CPOL 6.2K 13
Rate this:
Please Sign up or sign in to vote.
overloading short-circuit operator c# is not possible directly here is some tips for how get custom short-circuit operator

Introduction

Here we will discuss how to overload short-circuit operator on c#, before reading this article you have knowledge of operator overloading in c#(pre-requisite). Short-circuit operator are(&& and ||).they work almost the same as ampersand(&) and simple pipeline(|).but there are some differences in the working of short-circuit operator and ampersand single pipeline.

bool a=false;
bool b = true;
If(a & b)
//some code
If(a && b)
//some code

For a layman both expression will work the same and will generate the same output but for programmer there is difference between working of short-circuit(&&) and ampersand (&).

Working of short-circuit

In c# short-circuit operator can used in bool expression only . it will return true and according to the condition in the control statement. If short-circuit find operand that can reflect the result of expression it will stop checking the remaining operands and execute the condition true or false the is being reflected by operand. In the above code in if statement && will find that a is false and in AND operator all the operand must be true in order to execute if statement. In this case a is false so it will not check b and will transfer control to else statement .&& and || operators do not work with integer or any other type except boolean.

Working of ampersand or single pipeline operator

the main difference between short-circuit and single pipeline/ampersand operator is (&or |) can work with integer too. It compare the two operand bitwise and AND them. The result can store in other integer variable;

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

other difference is (&or|)operator check all the condition even if the result of control statement is being reflected buy 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 to over load short-circuit operator directly just like +,-,/,|,&etc. But there are certain rules if we fulfill them when can use short-circuit operator for user define data type or in simple can overload them. In fact we do not overload them but if the condition are fulfill they are overload by compiler logically.

Rules for overloading short-circuit operator.

  1. |and & must be overloaded for the give class.
  2. |and & must return object of the class for which they are overloaded
  3. |and& must have reference to object of the class for which they are overloaded
  4. True and false statement must be overloaded .

If above 4 rules are fulfill by our program we can use the short-circuit operator for user define data type in overloaded form with out actually overloading them.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace operatorOverLoading
{

    class demension
    {
        private int height;
        private int width;
        //no argument constructor for class
        public demension()
        {
            height = 0;
            width = 0;
        }
//two argument constructor for class
        
        public demension(int h, int w)
        {
            height = h;
            width = w;

        }
//display mathod
        public void show()
        {
            Console.WriteLine("height  :" + height);
            Console.WriteLine("width  :" + width);
        }
//overloaded | operator
        public static demension operator |(demension d1, demension d2)
        {
            if (((d1.width != 0) || (d1.height != 0)) | ((d2.width != 0) || (d2.height != 0)))
                return new demension(1, 1);
            else
                return new demension(0, 0);

        }
//overloaded & operatore       
        public static demension operator &(demension d1, demension d2)
        {
            if (((d1.width != 0) && (d1.height != 0)) & ((d2.width != 0) && (d2.height != 0)))
       
                return new demension(1, 1);
            
            else
                return new demension(0, 0);
            
        }
        
       
  //overloaded true statement     
        public static bool operator true(demension op)
        {
            if ((op.width != 0) || (op.height != 0))
                return true; // at least one coordinate is non-zero 
            else
                return false;
        }
  //overloaded false statement     
        public static bool operator false(demension op)
        {
            if ((op.width == 0) && (op.height == 0))
                return true; // all coordinates are zero 
            else
                return false;
        }
       
       
    }
    class Program
    {
        static void Main(string[] args)
        {
// creating objects
            demension a = new demension(5, 6);
            demension b = new demension(10, 10);
            demension c = new demension(0, 0);
//call to && for user define data type           
           if (b && a) Console.WriteLine("a && c is true.");
            else Console.WriteLine("a && c is false.");
//call to || for user define data type
            if (a || b) Console.WriteLine("a || b is true.");
            else Console.WriteLine("a || b is false.");
//can also call to | for user define data type
            if (a | c) Console.WriteLine("a || c is true.");
            else Console.WriteLine("a || c is false.");
            
            Console.ReadKey();
        }
    }
}

How the code will work

If (b&&a)

At first control will transfer to false operator to check it is false or not for operand a if the false statement return true the short-circuit operator will not check b and control will transfer to else statement . If false statement return false & operator will be call for b operand and check if statement inside & operator is true.if so two argument constructor will be call with (1,1) and this newly created object is return to b operand and true statement is check if satisfy will return true if not will return false. if statement inside & operator is false.if so two argument constructor will be call with (0,0) and this newly created object is return to b operand and true statement is check if satisfy will return true if not will return false. The according to that if or else will be executed in main

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

yousafzai amazai

Pakistan Pakistan
No Biography provided
Follow on   Twitter   Google+

Comments and Discussions

 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun17-Oct-14 3:39
memberHumayun Kabir Mamun17-Oct-14 3:39 
GeneralMy vote of 5 Pin
CatchExAs15-Jul-14 13:29
professionalCatchExAs15-Jul-14 13:29 
SuggestionOverall good Pin
Scott Corbett8-Jul-14 2:57
memberScott Corbett8-Jul-14 2:57 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150520.1 | Last Updated 6 Jul 2014
Article Copyright 2014 by yousafzai amazai
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid