Operators
Intro
Operators are an addition to programming languages, so we do not have to use methods for everything. Usually there are built-in operators and some programming languages, like C#, support also user-defined operators.
List of operators in C# (sorted by order of execution)
Operators use Operands
int sum;
sum = 3 + 5 ;
//operand operator operand operator operand
Both operators in the above example are binary operators, because they need two operands to work.
The increment and decrement oprator are unary operators, which only use one operand:
int i = 3;
i++; // Unary opertaor
Prefix and Postfix Operators
int i = 10;
if (i++ == 10) {
Console.WriteLine("Condition True"); // Executed
}
Console.WriteLine(i);
Line 2: Expression is evaluated and then the increment is executed.
int i = 10;
if (++i == 10) {
Console.WriteLine("Condition True"); // Not executed
}
Console.WriteLine(i);
(Please notice the difference in Line 2: i++ vs. ++i)
Line 2: The increment is executed and then the expression is evaluated.
Trenary operator
string text;
int num = 10;
if (num == 10) {
text = "Condition True";
} else {
text = "Condition False";
}
Console.WriteLine(text);
string text;
int num = 10;
text = ( (num == 10) ? "Condition True" : "Condition False" );
Console.WriteLine(text);
Shortend:
text = num == 10 ? "True" : "False";