C Sharp for Beginners/Operators

Operators perform actions on data. There are three types of operators in C#:

  • A unary operator has the form [operator][object]. An example is the negation operator: -number gives you number with the opposite sign (if number was 12 you would get -12).
  • A binary operator has the form [object 1] [operator] [object 2]. An example is the assignment operator: number = 1234 sets number to 1234.
  • A ternary operator has three objects on which it acts. C# only has one ternary operator, the conditional operator: number == 1234 ? "good" : "bad" gives you "good" if number is equal to 1234, but "bad" if number is not equal to 1234.

You can combine operators in almost any way you like. Here is an example incorporating many different operators:

class OperatorsExample
{
    public static void Main()
    {
        int number = 0;
        float anotherNumber = 1.234;
        string someText = "lots of ";
        
        number = number + 4; // number is now 4
        anotherNumber += 2; // this is a shorter version of the above; it adds 2 to anotherNumber, making it 3.234
        someText += "text"; // someText now contains "lots of text"
        number = -number; // number is now -4
        anotherNumber -= number * 2; // subtracts -8 from anotherNumber, making anotherNumber 11.234.
        
        number++; // increments number, making it -3
        anotherNumber = number++; // increments number but sets anotherNumber to the original number.
        // number is now -2, and anotherNumber is -3.
        number--; // decrements number, making it -3
        anotherNumber = --number; // decrements number and sets anotherNumber to the new number.
        
        anotherNumber = number = 1; // sets both anotherNumber and number to 1.
        
        bool someBoolean;
        
        // sets someBoolean to true if anotherNumber equals number, otherwise sets it to false
        someBoolean = anotherNumber == number;
    }
}

Prefix and Postfix edit

The ++ and -- operators can be placed before (prefix) or after (postfix) variables. There is a subtle difference between the two; if placed before, it increments or decrements and then returns the new value, and if placed after, it increments or decrements and returns the old value. For example:

int x, y;

x = 0;
x++;
++x;

// x is now 2...
y = x++; // y is now 2, x is now 3

x = 2; // x is now 2 again...
y = ++x; // y is now 3, x is now 3