What Does Operators Mean?
Operators, in C#, are symbols used within an expression or statement to specify the operations to be performed during evaluation of the expression. Operators are program elements that can be applied to one or more operands in an expression to perform computations. The operands used with the operator can be literals, fields, local variables and expressions.
In general, operators help in building expressions that form the primary means to work with data stored in constants and variables.
Although all the C# operators are provided with predefined implementation that are used in any expression containing built-in types, they can be overloaded to modify the behavior when applied to user-defined types. Operators such as checked and unchecked help in providing the option to handle or ignore exceptions related to overflow caused during arithmetic operations.
Techopedia Explains Operators
Like C++ operators, C# operators also have precedence and asociativity which determine the order of evaluation of operators in an expression. Based on the number of operands used with the operator, operators are classified as unary (single operand), binary (two operands) and ternary (three operands).
User-defined types can overload an operator by defining it as a static member function using the keyword, ‘operator’ with public level of accessibility. Some operators can only be overloaded with few restrictions.
For example, the operator ‘==’ can be used to compare two objects of immutable value type for which the operator is overloaded in the user-defined type of the object for comparing the value equality instead of reference equality.
The various types of C# operators that are used for specific functionalities include:
- Assignment (=) : used to assign the result of an expression to a variable
- Short-hand assignment(+=,-=,*=,/=,%=,&=,|=,^=,<<=,>>=): for shortening the common assignment operations
- Arithmetic (+,-,*,/,%) : for constructing mathematical expressions
- Increment and decrement operators (++ and --): shortcut for incrementing or decrementing the value by 1
- Comparison (==,>,<,>=,<=,!=): for performing comparison that control the program flow
- Boolean logical operator (!, &&, ||, ^): for performing Boolean logical operations
- Bitwise manipulation (&,|,^,>>,<<): for manipulating each bit of integer values
- Type testing(is, as): to check or convert the type of an object
- Pointer manipulation(*,&,->,): for operations performed directly on pointers in unsafe context
- Overflow exception (checked and unchecked): option to check or avoid checking overflow on values
- Ternary operator (?:):used for making decisions