7 Things about C#: Operators
source link: https://medium.com/seven-things-about-c/7-things-about-c-operators-ae4fad0af6c9
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
7 Things about C#: Operators
Every programming language has operators — the syntax that transforms values from one form to another. Think math, comparison, and bitwise transformations. Here, we discuss not only operators that are common to most general purpose languages, but also a few that are idiomatic to C#.
1 — Mathematical operators are algebraic
The general rule of using math operators is they evaluate from left to right, except that multiplication, *
, and division, /
, have precedence over addition, +
, and subtraction, -
. Here’s an example that expresses the nuances of operator precedence and associativity.
float result = 1 + 3 * 4;
The result
is 13. That’s because multiplication has precedence over addition. We multiply 3 * 4 to get 12 and then add 1 to get 13. That said, if you needed to add the 1 and 3 first, you can use this:
result = (1 + 3) * 4;
This time, the result
is 16 because parenthesis have precedence and allow you to manage the order of operations that you need.
Here’s a list of all of the C# operators. Operators at the top of the list have higher precedence than lower. Operators in the same category evaluate from left to right, as specified in code.
We’ll cover several of these operators here and catch up to the rest as we add more articles.
You’ve seen conditional expressions in earlier articles, which we’ll take another look at next.
2 — AND and OR operators are nuanced
You already learned about &&
and ||
operators in the If Statements article. However, these operators have interesting in their short circuiting behavior. Essentially, the left hand side of the operation can determine if the right hand side runs. Here’s an example:
bool internalCondition;
bool EvalCondition()
{
Console.WriteLine("EvalCondition Running...");
internalCondition = true;
return internalCondition;
}
bool…
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK