An operator performs the operations on operands. The combination of operands and operators are called expressions. There are lots of operators in C- Sharp language. The operators of an expression indicate which operations to apply to the operands. Operators in programming languages are taken from mathematics. An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. Programmers work with data. The operators are used to process data. An operand is one of the inputs (arguments) of an operator.
C-Sharp provides the following type of operators:
(Note: Assume variable A has 20 and B has 5.)
Arithmetic operators perform addition, subtraction, multiplication, division, and remainder operations. This is all familiar from the mathematics.
Relational operators perform the conditional operations. These operators return boolean type value true or false.
There are three logical operators. The boolean keyword is used to declare a Boolean value.
The ||, and && operators are short circuit evaluated. Short circuit evaluation means that the second argument is only evaluated if the first argument does not suffice to determine the value of the expression: when the first argument of the logical and evaluates to false, the overall value must be false; and when the first argument of logical or evaluates to true, the overall value must be true. Short circuit evaluation is used mainly to improve performance.
The assignment operator = assigns a value to a variable. A variable is a placeholder for a value. In an equation, the = operator is an equality operator. The left side of the equation is equal to the right one.
Decimal numbers are natural to humans. Binary numbers are native to computers. Binary, octal, decimal, or hexadecimal symbols are only notations of the same number. Bitwise operators work on bits and perform bit by bit operation. This operator’s work with bits of a binary number. The truth tables for &, |, and ^ are as follows:
Assume if A = 60; and B = 13; now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The operator precedence tells which operators are evaluated first. The precedence level is necessary to avoid ambiguity in expressions.
For example x = 5 + 2 * 4, here, x is assigned 13, not 40 because operator * has higher precedence than +, so it first gets multiplied with 2*4 and then adds into 7. Expressions inside parentheses are always evaluated first so we can use parentheses to change the order of evaluation.
The following table shows common C# operators ordered by precedence (highest precedence first):