Behind the Scenes Look at C#: Operators
(Page 1 of 8 )
Have you ever wanted to gain an indepth knowledge of C# operators? This article, the first in a series, gets you off to a good start. It covers arithmetic operators (including unary arithmetic operators), relational operators, logical operators, assignment operators, the ternary operator, and operator precedence.
The phrase "programming language operators" comes from the fact that operators are symbols and characters (as we will see later) that have been defined to perform an operation. I want make a note at this point before we go further that, to the runtime, there's no existence for operators, because the C# compiler generates method calls instead of using operators. For now, think of the expression x + y in C# as "int Add(x,y)" in the MSIL. That's why I will call x and y arguments to the operator, because those are in fact method arguments. Some of you would call them operands; that term is fine, too.
When using operators, there must be a return value of the performed operation (which is much more like a return value of a method call). The operator arguments may be singular; in this case, we will call the operator a unary operator. You may be dealing with two arguments, in which case they would be called binary operators, and new to C# is the ternary operator, which takes three arguments (?:).
Also note that operators are defined on the basis of type, so the .NET Framework permits us to write something like result = x + y; (where all these variables are primitive types), but you can't assume that Employee = Employee + Employee (where Employee is a user defined class). You need to overload the plus operator in order for this statement to work. Operator overloading will be discussed in detail in the second part of this article series.
Most C# operators are overloaded to work with primitive data types such as byte, integer, single, double and decimal. For the string class, C# overloads the += assignment operator and the + operator, as we will see. Also, you can assign objects to references by using the = assignment operator (the System.Object overloads the = operator). As a consequence of overloading the assignment operator (=) on the object class, overloading the == and != operators is a must for the object class, too.
We will discuss the various categories of C# operators, including arithmetic operators, relational operators, logical operators, and assignment, conditional and type Operators. We'll be throwing a lot of symbols around, so let's begin to discuss C# operators categories by the type of operations they perform on their arguments.
Next: Arithmetic Operators >>
More C# Articles
More By Michael Youssef