C# Operators

Operators are the small symbols that tell C# to perform an action on values. You already used one every time you wrote =, but there are many more. Operators let you add numbers, compare values, combine conditions, and shorten common patterns. This page gives you the big picture, and the following pages zoom into each group.

What is an operator?

An operator works on one or more values, called operands, and produces a result. For example, in the expression 5 + 3 the plus sign is the operator, while 5 and 3 are the operands. The whole expression evaluates to 8.

A simple operator in action

int a = 5;
int b = 3;
int sum = a + b;
Console.WriteLine(sum); // 8

The main groups of operators

C# divides operators into several families based on what they do. You will meet each of these in detail on the next pages, but here is the map so you know where you are heading.

Operator groups covered in this topic

GroupPurposeExamples
ArithmeticDo math with numbers+ - * / %
AssignmentStore or update values= += -= *=
ComparisonCompare two values, result is bool== != > < >= <=
LogicalCombine true/false conditions&& || !
  • Arithmetic operators return a number, such as 10 / 2 giving 5.
  • Comparison and logical operators return a bool, either true or false.
  • Assignment operators change what is stored inside a variable.

One example from each group

int score = 10;      // assignment
score += 5;          // assignment (now 15)
int total = score * 2; // arithmetic (30)
bool passed = total >= 20; // comparison (true)
bool win = passed && total < 100; // logical (true)
Console.WriteLine(win);
Note: When several operators appear in one expression, C# follows precedence rules, similar to math class. Multiplication and division happen before addition and subtraction. When in doubt, add parentheses to make the order clear and readable.

Exercise: C# Operators

What does the expression 7 / 2 evaluate to when both operands are int?