Operator Precedence1:55 with Jay McGavren
Most programming languages let you chain math operations together, and C# is no exception. The order of operations you were taught in math class applies in C# too.
- Most programming languages let you chain math operations together, and C# is no exception:
Console.WriteLine(1 + 2 + 3);
- Order of operations you were taught in math class applies in C# too.
Console.WriteLine(1 + 2 * 3);
- If you didn't have order of operations, you'd assume that you add
2, getting 3, and then multiply
3 * 3to get
9. But that's not what we get.
- Instead we get 7.
- This is because of order of operations. In chained math operations, multiplication and division operations always come first , and addition and subtraction second .
- C# respects this concept by following something called operator precedence. That is, the evaluation of some operators precedes the evaluation of some other operators. The multiplication and division operators have higher precedence that addition and subtraction operators.
- So that's why when we evaluate
1 + 2 * 3, we get
9. The multiplication operator has higher precedence than the addition operator, so we do the multiplication first, giving us
6. We then add
6, giving us 7.
- But suppose we wanted to ensure that the addition operation occurs first. If we were working in a math textbook, we'd add parentheses around the operation to indicate it should go first, no matter what:
(1 + 2) * 3.
- And that same notation works in C#. C# will always evaluate math operations within parentheses first, before it goes on to evaluate the rest of the expression. So with the parentheses,
1 + 2is evaluated first, giving
3, and then that's multiplied by
If you're not comfortable with operator precedence, or you want to learn more, visit these links.
You need to sign up for Treehouse in order to download course files.Sign up