C# Operators
An operator is a sign that makes a value from other values. The sign + is an operator, and so are the signs that change or combine values.
Up and down by one
The ++ sign adds 1 to count. The -- sign then takes 1 away again.
using System;
class Program
{
static void Main(string[] args)
{
int count = 5;
count++;
Console.WriteLine(count);
count--;
Console.WriteLine(count);
}
}Short update signs
The += sign adds 4 to score. The *= sign then multiplies the new score by 3.
using System;
class Program
{
static void Main(string[] args)
{
int score = 6;
score += 4;
Console.WriteLine(score);
score *= 3;
Console.WriteLine(score);
}
}Joining bool tests
The && sign gives true because both sides are true. The || sign also gives true, and ! flips the first value to false.
using System;
class Program
{
static void Main(string[] args)
{
bool isSunny = true;
bool isWarm = true;
Console.WriteLine(isSunny && isWarm);
Console.WriteLine(isSunny || isWarm);
Console.WriteLine(!isSunny);
}
}Parentheses set the order
Multiplication runs before addition in the first line. Parentheses in the second line make the addition run first.
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(2 + 3 * 4);
Console.WriteLine((2 + 3) * 4);
}
}Example
using System;
class Program
{
static void Main(string[] args)
{
int items = 3;
items += 2;
Console.WriteLine("Items: " + items);
double price = 4.5;
double total = items * price;
Console.WriteLine("Total: " + total);
bool bigOrder = items > 4 && total > 20;
Console.WriteLine("Big order: " + bigOrder);
}
}Key points
- The sign ++ adds 1 to a variable, and -- takes 1 away.
- The sign += adds a value to a variable in one step.
- The sign *= multiplies a variable by a value in one step.
- The sign && gives true only when both sides are true.
- The sign || gives true when at least one side is true.
- The sign ! flips true to false and false to true.
- Parentheses set the order of a calculation, just like in maths.
In this example, items starts at 3 and += 2 raises it to 5, so the first line prints Items: 5. The total multiplies 5 items by the price 4.5, and the second line prints Total: 22.5. Both tests in the last line are true, so it prints Big order: True.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz C# Compiler
Exercise
What does score hold after int score = 10; and then score += 5;?