Changes

Jump to: navigation, search

C Sharp Operators and Expressions

2,019 bytes added, 19:35, 14 January 2008
C# Operator Precedence
== C# Operator Precedence ==
 
When humans evaluate expressions, they usually do so starting at the left of the expression and working towards the right. For example, working from left to right we get a result of 300 from the following expression:
 
10 + 20 * 10 = 300
 
This is because we, as humans, add 10 to 20, resulting in 30 and then multiply that by 10 to arrive at 300. Ask C# to perform the same calculation and you get a very different answer:
 
<pre>
int x;
 
x = (10 + 20) * 10;
 
System.Console.WriteLine (x)
</pre>
 
The above code, when compiled and executed, will output the result 210.
 
This is a direct result of ''operator precedence''. C# has a set of rules that tell it in which order operators should be evaluated in an expression. Clearly, C# considers the multiplication operator (*) to be of a higher precedence than the addition (+) operator.
 
Fortunately the precedence built into C# can be overridden by surrounding the lower priority section of an expression with parentheses. For example:
 
<pre>
int x;
 
x = 10 + 20 * 10;
 
System.Console.WriteLine (x)
</pre>
 
In the above example, the expression fragment enclosed in parentheses is evaluated before the higher precedence multiplication resulting in a value of 300.
 
The following table outlines the C# operator precedence order from highest precedence to lowest:
 
<table>
<th>Operators</th>
<tr>
<td>+ - ! ~ ++x --x (T)x</td>
<tr>
<td>* / %</td>
<tr>
<td>+ -</td>
<tr>
<td><< >></td>
<tr>
<td>< > <= >= is as</td>
<tr>
<td>== !=</td>
<tr>
<td>&</td>
<tr>
<td>^</td>
<tr>
<td>|</td>
<tr>
<td>&&</td>
<tr>
<td>||</td>
<tr>
<td>:?</td>
<tr>
<td>= *= /= %= += -= <<= >>= &= ^= |=</td>
<table>
 
It should come as no surprise that the assignment operators have the lowest precedence since you would not want to assign the result of an expression until that expression had been fully evaluated.
 
Don't worry about memorizing the above table. Most programmers simply use parentheses to ensure that their expressions are evaluation in the desired order.
== Compound Assignment Operators ==

Navigation menu