Csharp/CSharp Tutorial/Operator/Operator Precedence

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

multiple arithmetic operators

<source lang="csharp">class MainClass {

 public static void Main()
 {
   
   System.Console.WriteLine("3 * 4 / 2 = " + 3 * 4 / 2);
 }

}</source>

3 * 4 / 2 = 6

Operator precedence, with () and without ()

<source lang="csharp">class MainClass {

 public static void Main()
 {
   int myInt = 2 + 5 * 10;
   System.Console.WriteLine("2 + 5 * 10 = " + myInt);
   myInt = (2 + 5) * 10;
   System.Console.WriteLine("(2 + 5) * 10 = " + myInt);
   myInt = 2 * 20 / 5;
   System.Console.WriteLine("2 * 20 / 5 = " + myInt);
 }

}</source>

2 + 5 * 10 = 52
(2 + 5) * 10 = 70
2 * 20 / 5 = 8

Order of Precedence for Expressions

<source lang="csharp">Precedence Operator 1 array "[ ]",

                     checked , 
                     function "()", 
                     member operator ".", 
                     new, 
                     postfix decrement , 
                     postfix increment, 
                     typeof, 
                     and unchecked operators

2 unary addition "+",

                     casting "()", 
                     one complement "~", 
                     not "!", 
                     prefix decrement, 
                     prefix increment, 
                     unary subtraction "-"operators

3 division "/",

                     and modulus "%", 
                     multiplication "*" operators

4 binary addition "+" and binary subtraction "-" operators 5 left-shift "<<" and right-shift ">>" operators 6 as,

                     is, 
                     less than "<", 
                     less than or equal to "<=", 
                     greater than ">", 
                     greater than or equal to ">=" operators

7 equals "==" and not equal "!=" operators 8 Logical And "&" operator 9 Logical XOR "^" operator 10 Logical Or "|" operator 11 Conditional And "&&" operator 12 Conditional Or "||" operator 13 Conditional "?:" operator 14 Assignment "=",

                     compound "*=, /-=, %=, +=, -=, <<=, >>=, &=, ^=, and |=", 
                     and null coalescing "?" operator</source>

The Precedence of the C# Operators

<source lang="csharp">Highest () [] . ++(postfix) --(postfix) checked new sizeof typeof unchecked ! ~ (cast) +(unary) -(unary) ++(prefix) --(prefix)

  • /  %

+ - << >> < > <= >=is

= !

& ^ | && || ?:

op

Lowest</source>