What is the difference between & and && operators in C#

前端 未结 9 921
误落风尘
误落风尘 2020-12-02 17:03

I am trying to understand the difference between & and &&operators in C#. I searched on the internet without success. Can somebody plea

9条回答
  •  南笙
    南笙 (楼主)
    2020-12-02 17:41

    Below example and explanation's may help.

    Example:

        public static bool Condition1()
        {
            return false;
        }
    
        public static bool Condition2()
        {
            return true;
        }
    

    1. Logical Operator

    & (ampersand) Logical AND operator

    | (pipeline) Logical OR operator

    Used for ensuring all operands are evaluated.

    if(Condition1() & Condition2())
    {
      Console.WriteLine("This will not print");
    
      //because if any one operand evaluated to false ,  
      //thus total expression evaluated to false , but both are operand are evaluated.
    }
    
     if (Condition2() | Condition1())
     {
       Console.WriteLine("This will print");
    
       //because any one operand evaluated to true ,  
      //thus total expression evaluated to true , but both are operand are evaluated.
     }
    

    2. Conditional Short Circuit Operator

    && (double ampersand) Conditional AND operator

    || (double pipeline) Conditional OR operator

    Used for Skipping the right side operands , Has Side effects so use carefully

    if (Condition1() && Condition2())
    {
       Console.WriteLine("This will not print");
    
       //because if any one operand evaluated to false,
       //thus total expression evaluated to false , 
       //and here the side effect is that second operand is skipped 
       //because first operand evaluates to false.
    }
    
    if (Condition2() || Condition1())
    {
       Console.WriteLine("This will print");
    
      //because any one operand evaluated to true 
      //thus remaining operand evaluations can be skipped.
    }
    

    Note:

    To get better understanding test it in console sample.

    References

    dotnetmob.com

    wikipedia.org

    stackoverflow.com

提交回复
热议问题