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

前端 未结 9 869
误落风尘
误落风尘 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:33

    & can be used on either integral types (like int, long etc.) or on bool.

    When used on an integral type, it performs a bitwise AND and gives you the result of that. When used on a bool, it performs a logical AND on BOTH its operands and gives you the result.

    && is not used as a bitwise AND. It is used as a logical AND, but it does not necessarily check both its operands. If the left operand evaluates to false, then it doesn't check the right operand.

    Example where this matters:

    void Action() 
    {
        string name = null;
        if(name != null && name.EndsWith("ack"))
        {
            SomeOtherAction();
        }
    }
    

    If name is null, then name.EndsWith("ack") will never get executed. It is smart enough to know if the left operand is false, then the right operand doesn't need to be evaluated (aka "short-circuiting"). That's good because calling a method on null will throw a NullReferenceException.

    If you changed it into if(name != null & name.EndsWith("ack")), both sides would get evaluated and it would throw a NullReferenceException.

    One detail: & can also be a unary operator (so it has one operand) in an unsafe context. It will give the address of a value or object. It's not important though, as most people don't ever have to touch this part of the language.

    0 讨论(0)
  • 2020-12-02 17:33

    & is a bitwise operator and && is a logical operator that applies to bool operands.

    0 讨论(0)
  • 2020-12-02 17:33

    Hai Friend, The Operator &&(Logical Operator) is used in conditional statements. For Instance

    if(firstName == 'Tilsan' && lastName == 'Fighter')
    {
          Response.Write("Welcome Tilsan The Fighter!");
    }
    

    the Response.Write statement will run only if both variables firstName and lastName match to their condition.

    Whereas & (Bitwise Operator)operator is used for Binary AND operations, i.e., if we write:

    bool a, b, c;
    
    a = true;
    b = false;
    
    c = a & b;
    
    Response.Write(c); // 'False' will be written to the web page
    

    Here first Binary And operation will be performed on variables a and b, and the resultant value will be stored in variable c.

    0 讨论(0)
  • 2020-12-02 17:36

    Easy way to look it is logical & will evaluate both sides of the & regardless if the left side is false, whereas the short-circuit && will only evaluate the right side if the left is true.

    d=0;
    n=10;
    
    // this throws divide by 0 exception because it evaluates the 
    //      mod even though "d != 0" is false
    if ( (d != 0) & (n % d) == 0 ) 
       Console.Writeline( d + " is a factor of " + n);
    
    // This will not evaluate the mod.
    if ( (d != 0) && (n % d) == 0 ) 
       Console.Writeline( d + " is a factor of " + n);
    
    0 讨论(0)
  • 2020-12-02 17:38

    Strongly recommend this article from Dotnet Mob : http://codaffection.com/csharp-article/short-circuit-evaluation-in-c/

    -&& is short-circuit logical operator

    For AND operations if any of the operand evaluated to false then total expression evaluated to false, so there is no need to evaluate remaining expressions, similarly in OR operation if any of the operand evaluated to true then remaining evaluation can be skipped

    -& operator can be used as either unary or binary operator. that is, unary & can be used to get address of it’s operand in unsafe context.

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题