C Sharp

Expressions and Operators

In this tutorial, we'll take a look at the most basic part of any programming language: its ability to express assignments and comparisons through the use of operators. We'll look at what operators are and how operator precedence is determined in C#, and then we'll delve into specific categories of expressions for doing such things as performing math, assigning values, and making comparisons between operands.

Operators Defined

An operator is a symbol that indicates an operation to be performed on one or more arguments. This operation produces a result. The syntax used with operators is a bit different than that used with method calls, but the C# format of an expression using operators should be second nature to you. Like operators in most other programming languages, C# operator semantics follow the basic rules and notations we learned as children in mathematics classes. The most basic C# operators include multiplication (*), division (/), addition and unary plus (+), subtraction and unary minus (-), modulus (%) and assignment (=).

Operators are specifically designed to produce a new value from the values that are being operated on. The values being operated on are called operands. The result of an operation must be stored somewhere in memory. In some cases the value produced by an operation is stored in the variable containing one of the original operands. The C# compiler generates an error message if you use an operator and no new value can be determined or stored. In the following example, the code results in nothing being changed. The compiler generates an error message because writing an arithmetic expression that doesn't result in a change to at least one value is generally a mistake on the part of the developer.

class NoResultApp
    public static void Main()
        int i;
        int j;

        i + j; // Error because call is not assigned to a variable.

Most operators work only with numeric data types such as Byte, Short, Long, Integer, Single, Double, and Decimal. Some exceptions are the comparison operators (==" and "!=) and the assignment operator (=), which can also work on objects. In addition, C# defines the + and += operators for the String class and even allows for the use of increment operators (++) and (--) on unique language constructs such as delegates. I'll get into that last example in tutorial "Delegates and Event Handlers."

by BrainBellupdated