#28 – Operator Precedence

Each operator has an associated precedence, which indicates the order in which the operators are evaluated when evaluating the  expression.

When an expression has operators of the same precedence, they are evaluated according to their rules of associativity–left to right for all binary expressions, except for assignment and conditional operators, which are right to left.

Here are the C# operators, in order of precedence.  Operators in each group are of equal precedence.

  • Primary:  x.y  f(x)  a[x]  x++  x–  new  typeof  checked  unchecked
  • Unary:  +  –  !  ~  ++x  –x  (T)x
  • Multiplicative:  *  /  %
  • Additive:  +  –
  • Shift:  <<  >>
  • Relational:  <  >  <=  >=  is  as
  • Equality:  ==  !=
  • Logical AND:  &
  • Logical XOR:  ^
  • Logical OR:  |
  • Conditional AND:  &&
  • Conditional OR:  ||
  • Conditional:  ?:
  • Assignment:  =  *=  /=  %=  +=  -=  <<=  >>=  &=  ^=  |=

Precedence can be changed by using parentheses, the inner expressions being evaluated first.

More

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

3 Responses to #28 – Operator Precedence

  1. Pingback: #1,074 – Use Parentheses in Expressions to Make Code More Readable | 2,000 Things You Should Know About C#

  2. Pingback: #1,075 – Operator Precedence Doesn’t Affect Operand Evaluation Order | 2,000 Things You Should Know About C#

  3. kai zhou says:

    Precedence and associativity.
    Nice work, Sean. Thank you.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: