C# Operators and Math

Learn C# operators with simple explanations of arithmetic, assignment, comparison, logical operators, integer division, precedence and Math class methods.

Lesson 3 of 43Beginner34 min read

When you write a C# program, you often need to add prices, compare ages, update scores, or check whether someone meets a condition. C# operators make these tasks possible. An operator is a symbol that tells the program to perform an action on one or more values. Those values are called operands. For example, in 8 + 3, the + symbol is the operator, while 8 and 3 are its operands.

Operators in C# are not limited to calculations. Some perform mathematical operations, others compare values, and others combine true-or-false conditions. Learning how they work helps you read unfamiliar code and write your own programs with fewer mistakes. You will see them in simple calculators, games, shopping applications, login forms, and almost every other kind of software.

This beginner-friendly guide explains the main types of operators in C#, how they work with different numeric data types, and when to use the built-in Math class. You'll also learn why integer division sometimes gives an unexpected answer, how operator precedence changes a calculation, and how to avoid common errors. Each topic starts with a plain-language explanation so you can understand the idea before trying the code examples below.

What are the types of operators in C#?

C# has several operator groups, and each group solves a different problem. Arithmetic operators calculate numeric results. Assignment operators put values into variables or update existing values. Comparison operators, also called relational operators, check how two values relate to each other. Logical operators help you work with multiple conditions. C# also includes increment and decrement operators, bitwise operators, a ternary conditional operator, and operators for handling null values.

You may also hear an operator described as unary, binary, or ternary. These terms tell you how many operands the operator uses, not what kind of work it performs. A unary operator works with one operand, such as !isReady. A binary operator works with two, such as price + tax. The conditional ?: operator is ternary because it works with a condition and two possible results.

For beginners, it is easier to learn operators by purpose rather than memorize every symbol at once. Start with basic calculations and assignments. Then move to comparisons and logical conditions, which become especially useful when learning if statements and loops. More specialized operators will make sense once these foundations feel familiar.

Arithmetic operators in C#

C# arithmetic operators perform the basic mathematical calculations you already know from school. They are used with numeric values stored in variables or written directly in expressions. An expression is a combination of values, variables, and operators that produces a result. The five arithmetic operators you will use most often are addition +, subtraction -, multiplication *, division /, and remainder %.

OperatorMeaningExampleResult
+Addition5 + 27
-Subtraction5 - 23
*Multiplication5 * 210
/Integer division5 / 22
/Floating-point division5.0 / 22.5
%Remainder5 % 21

The addition operator combines numbers to find a total. You might use it to calculate a bill, combine two scores, or count the number of items in a cart. Subtraction finds the difference between values, such as money remaining after a purchase. Multiplication is useful when the same amount appears several times, and division helps you split a quantity into equal parts.

One detail that surprises new programmers is that the same operator can behave differently depending on the data type. The + operator adds numeric values, but it can also join strings. Similarly, division produces different results depending on whether you work with whole numbers or floating-point values. Choosing an appropriate type is therefore part of writing correct mathematical calculations in C#.

For money, decimal is generally a better choice than double because it is designed for decimal arithmetic. For measurements and scientific calculations, double is often suitable. Use int when you need whole numbers, such as quantities or counts. These choices help prevent unexpected results as your programs become more complex.

Integer division and the modulus operator

C# integer division happens when both operands of / are integer types. The result keeps only the whole-number part and discards the fraction. For example, 7 / 2 produces 3, even if you later store that result in a double variable. The division has already happened before the result is assigned. If you want 3.5, make at least one operand a floating-point number, such as 7.0 / 2, or convert an operand before dividing.

This distinction matters when you calculate averages, percentages, or amounts that can contain decimal places. A beginner might expect dividing an integer total by an integer count to produce an exact average, but C# follows the operands' types. When working with decimal, use compatible decimal operands, such as 7m / 2m. Don't mix decimal and double values directly in an arithmetic expression, because C# does not automatically combine those types.

The C# modulus operator, written %, returns the remainder after division rather than the quotient. For instance, 17 % 5 gives 2 because three complete groups of five fit into seventeen, with two left over. This operator is useful when checking whether a number is even or odd: a number is even when number % 2 == 0.

Remainders also help with repeating patterns. A timer can use division to find completed hours and % to find the minutes left over. A game can use remainders to cycle through a fixed set of turns. However, remember that % in C# is a remainder operator, and its result can be negative when the left operand is negative. We will cover that detail later in this lesson.

Assignment operators and shortcuts

An assignment operator stores a value in a variable. The basic assignment operator is =. In score = 10, C# places the value 10 into score. It does not ask whether two values are equal; that job belongs to the comparison operator ==. Knowing the difference between = and == is important because the two symbols appear in different kinds of statements.

C# also supports compound assignment operators, which combine a calculation with an assignment. Instead of writing score = score + 5, you can write score += 5. Both forms express the idea of adding five to the existing score. Other common shortcuts include -=, *=, /=, and %=. They are especially helpful when a program updates the same variable repeatedly.

C#
int score = 10;
score += 5;    // 15
score -= 3;    // 12
score *= 2;    // 24
score /= 4;    // 6
score %= 4;    // 2

These shortcuts reduce repeated code, but the meaning should remain clear to someone reading your program. Use them for straightforward changes such as increasing points, reducing stock, or applying a multiplier. Be mindful of numeric types: dividing an int variable with /= still uses integer division, so fractional information may be lost. Compound assignments also follow C# conversion rules, which can sometimes differ from writing an expanded assignment by hand.

Increment and decrement operators

The C# increment and decrement operators change a variable by exactly one. Increment ++ increases its value, while decrement -- decreases it. These are common in counters, loops, and situations where something changes one step at a time, such as tracking lives remaining in a game.

There are two ways to write an increment: prefix ++x and postfix x++. When either expression appears alone as a statement, both increase x by one. The difference becomes important when you use the expression as part of a larger calculation. Prefix increment updates the value first and then supplies the new value. Postfix increment supplies the old value first and then updates the variable. The same distinction applies to --x and x--.

C#
int x = 5;
int before = x++;  // before is 5; x becomes 6
int after = ++x;   // x becomes 7; after is 7

For beginner-friendly code, keeping an increment or decrement on its own line is often the clearest choice. It avoids forcing readers to remember the order of changes inside a longer expression. When you do use prefix and postfix forms, pause to ask which value the surrounding expression receives.

Comparison and relational operators

C# comparison operators check whether values are equal or whether one value is greater or smaller than another. They are also called relational operators. Every ordinary numeric comparison produces a bool result: either true or false. These results are the foundation of decisions made with if statements, while loops, and other control-flow features.

OperatorMeaningExample
==Equal toage == 18
!=Not equal toscore != 0
>Greater thanprice > 100
<Less thantemperature < 0
>=Greater than or equal toage >= 18
<=Less than or equal toitems <= 10

Think of comparisons as questions that a program can answer. Is the user's age high enough? Is the basket total above a discount threshold? Are there any items left? Once you know the result, your code can choose what happens next. A comparison does not normally change the values being checked; it simply examines them.

The symbols = and == are easy to confuse because they look similar. Remember that a single equals sign assigns a value, while a double equals sign asks whether two values are equal. Also, string comparisons and comparisons involving custom types can follow additional rules. For this beginner lesson, focus on numeric comparisons and the bool results they produce.

Logical operators and short-circuit evaluation

C# logical operators let you combine or reverse conditions. They work with Boolean expressions, which are expressions that produce true or false. The three symbols beginners should learn first are && for logical AND, || for logical OR, and ! for logical NOT.

  • && returns true when both conditions are true.
  • || returns true when at least one condition is true.
  • ! reverses a Boolean value, changing true to false or false to true.

Imagine a website that allows someone to enter only if they have a valid ticket and the event is open. That decision needs AND. If a user can access a page because they are an administrator or the owner, that decision needs OR. If access is allowed only when an account is not blocked, you can use NOT.

C# uses short-circuit evaluation with && and ||. For &&, if the first condition is false, the entire AND expression must be false, so C# does not evaluate the second condition. For ||, if the first condition is true, the entire OR expression must be true, so C# skips the second condition. This behavior can make programs both safer and more efficient.

For example, name != null && name.Length > 0 checks that name exists before attempting to read its length. If name is null, C# does not evaluate name.Length, avoiding a null-reference error. As conditions grow, use parentheses and descriptive variable names to make their meaning obvious.

Operator precedence and associativity

When a C# expression contains several operators, operator precedence determines which operations are grouped together first. Multiplication, division, and remainder have higher precedence than addition and subtraction. That is why 10 + 5 * 2 gives 20, not 30: the multiplication belongs together before the addition. Parentheses let you explicitly change the grouping, so (10 + 5) * 2 gives 30.

C# operator associativity explains how operators with the same precedence are grouped. Many binary arithmetic operators associate from left to right. For example, 20 - 5 - 3 means (20 - 5) - 3, which gives 12. Assignment operators associate from right to left, so a = b = 10 first assigns 10 to b and then assigns that value to a. The conditional ?: operator and null-coalescing ?? operator are also right-associative.

Higher-to-lower precedenceCommon operators
Postfix and member accessx++, x--, .
Unary operations++x, --x, !, ~
Multiplication group*, /, %
Addition group+, -
Relational comparisons<, >, <=, >=
Equality comparisons==, !=
Conditional AND and OR&&, then ||
Null-coalescing and conditional??, then ?:
Assignment=, +=, -= and related forms

This simplified table highlights frequently used operators rather than every C# operator. Precedence and associativity describe how an expression is grouped; they are not a promise that every operand or method call runs in the same order as the table. In everyday code, parentheses are a simple way to make your intention clear. Even when they are not required, they can make a mixed calculation easier to understand and maintain.

Bitwise, ternary, and null-coalescing operators

Besides arithmetic and logical conditions, C# provides operators for specialized tasks. Bitwise operators act on the individual bits used to represent integer values. Some common bitwise symbols are & (AND), | (OR), ^ (exclusive OR), and ~ (bitwise complement). Shift operators such as << and >> move bit patterns left or right. You may encounter these in low-level programming, flags, device communication, or other situations that require working directly with binary data.

Do not confuse bitwise & with conditional logical &&. Both can be used with Boolean values, but && short-circuits while & evaluates both Boolean operands. When writing ordinary conditions, && and || are usually easier to understand and better suited to safe conditional checks.

The C# ternary operator ?:, also called the conditional operator, chooses between two expressions based on a condition. Its general shape is condition ? valueIfTrue : valueIfFalse. It is useful for choosing a short value such as a label or message. For complicated decisions, a regular if statement is often more readable.

The null-coalescing operator ?? supplies a fallback value only when the expression on its left is null. For example, displayName = name ?? "Guest" uses name when it is available and otherwise uses "Guest". A related operator, ??=, assigns a fallback only when the variable is currently null. These operators are helpful when working with optional data, but they should not be mistaken for checks against empty strings or zero.

Using the C# Math class

Arithmetic symbols handle common calculations, but many programs also need powers, square roots, rounding, or limits. The C# Math class, available through System.Math, provides ready-made methods for these operations. A method is a named piece of functionality that you call with the values it needs. Using built-in Math methods is clearer than recreating common mathematical formulas yourself.

Math.Abs returns the absolute value, which is the distance from zero without a negative sign. Math.Min finds the smaller of two values, while Math.Max finds the larger. Math.Clamp keeps a number inside a specified minimum and maximum. For example, a game can clamp a health score between zero and one hundred so the displayed amount stays within an allowed range.

To calculate powers, use Math.Pow. It raises one number to another power, such as Math.Pow(2, 3) for two cubed. To calculate a square root in C#, use Math.Sqrt. The ^ symbol does not mean exponentiation in C#; it is an exclusive-OR operator. This is a common beginner mistake when moving from written mathematics to programming.

For rounding numbers in C#, Math.Round rounds to a chosen precision, while Math.Floor and Math.Ceiling move toward the next lower or higher whole number, respectively. These methods behave differently for negative values as well, so choose the method that matches what your program needs. Math.Round(value, 2) can round to two decimal places, but formatting a number for display is not the same as changing the underlying numeric value.

Rounding, Random, and numeric data types

Rounding deserves extra care because there is more than one accepted rule for numbers exactly halfway between two possible results. By default, Math.Round uses round to nearest, ties to even, sometimes called banker's rounding. For example, Math.Round(2.5) returns 2, while Math.Round(3.5) returns 4. If your task requires halfway values to round away from zero, you can specify MidpointRounding.AwayFromZero.

For prices and totals, use decimal arithmetic and establish a rounding policy that matches your application or business rules. Floating-point types such as double can contain small representation differences, so not every decimal-looking value is stored exactly. Rounding should be deliberate, particularly when you calculate totals repeatedly. If you only need two decimal places on the screen, consider formatting the output instead of rounding the value used for later calculations.

Random numbers are not produced by the Math class. In modern .NET, Random.Shared gives access to a shared random-number generator suitable for many ordinary applications, including basic games and simulations. Random.Shared.Next(1, 7) returns an integer from 1 through 6. The lower bound is included, but the upper bound is excluded. That difference matters whenever you want to model a dice roll or select a valid array index. For security-sensitive random values, use an appropriate cryptographic random-number API instead of Random.Shared.

Overflow, division by zero, and NaN

Numeric data types have limits. For example, an int can hold only values within a specific range. When an integer calculation tries to produce a value outside that range, overflow occurs. In an unchecked context, many integer arithmetic operations wrap around instead of producing the mathematical result you expected. In a checked context, an overflow can raise an OverflowException, helping you detect a mistake before the incorrect number affects the rest of your program.

C#
int big = int.MaxValue;
int wrapped = unchecked(big + 1);   // -2147483648
int safe = int.MaxValue;
// int result = checked(safe + 1);  // throws OverflowException at runtime

Overflow checking is important for quantities, counters, financial data, and any operation where an incorrect value could cause a problem. Switching from int to long allows a larger range, but even long has a maximum value. The correct type and overflow policy depend on the values your application might handle. Note that decimal overflow throws an exception rather than silently wrapping like unchecked integer arithmetic.

Division by zero in C# also depends on the operand type. Integer division by zero and decimal division by zero throw a DivideByZeroException at runtime. A constant integer expression such as 10 / 0 is rejected by the compiler, so use variables when demonstrating the runtime exception. With double and float, division by zero can instead produce positive or negative infinity, or NaN (not a number).

OperationResult
Integer division by a zero-valued variableDivideByZeroException
decimal division by zeroDivideByZeroException
1.0 / 0.0Positive infinity
0.0 / 0.0NaN

NaN represents a value that is not a valid numeric result. It is unusual because comparing it with itself using == returns false. Instead, use double.IsNaN(value) when you need to detect it. Thinking about error cases early makes your C# mathematical calculations more reliable.

Remainders with negative numbers

The remainder operator can produce a surprising answer when negative numbers are involved. In C#, the remainder has the same sign as the left-hand operand when the remainder is nonzero. That means -7 % 3 evaluates to -1, rather than the positive result some people expect from a mathematical modulo operation.

This behavior matters when calculating a repeating index, rotating through days, or wrapping a position around the beginning of a collection. If you need a result between zero and a positive divisor minus one, you can normalize the remainder by taking it again after adding the divisor. The formula ((index % length) + length) % length works for a positive length, provided you have checked that the length is not zero.

C#
int index = -7;
int length = 3;
int wrapped = ((index % length) + length) % length;  // 2

For ordinary positive operands, you can use % directly without this additional step. When a problem involves negative positions or offsets, make sure you understand whether you want C#'s remainder behavior or a nonnegative wrapping result.

C# Basics Syntax

Operators


int a = 7 / 2;            // 3

double b = 7 / 2.0;       // 3.5

int r = 7 % 2;            // 1

int x = 0;
x += 1; x++; x--;

bool ok = age >= 18 && hasTicket;

bool any = isAdmin || isOwner;

bool not = !isBanned;

Math.Round(2.345, 2)      // 2.35

Math.Pow(3, 2)            // 9

Math.Clamp(150, 0, 100)   // 100

Random.Shared.Next(1, 7)  // 1 to 6

C# Basics Summary

  • + - * / and % do arithmetic; int / int drops the fraction.
  • % gives the remainder, useful for even checks and wrapping around.
  • += -= *= /= and ++ -- update variables in place.
  • Comparisons return bool; && || and ! combine them, with short-circuiting.
  • The Math class rounds, powers, square roots, clamps and more.

C# Basics Examples

Each example shows the code, the output it produces and what each part does.

Example 1

Splitting a bill

C#

int total = 95;

int people = 4;

Console.WriteLine(total / people);

Console.WriteLine(total % people);

Console.WriteLine((double)total / people);

decimal bill = 95.00m;

decimal tip = bill * 0.15m;

decimal each = (bill + tip) / people;

Console.WriteLine(Math.Round(each, 2));
Output

23

3

23.75

27.31
Line-by-line explanation
  1. Line 4Both values are ints, so the result is a whole number.
  2. Line 5% gives what's left over after dividing evenly.
  3. Line 6Casting one side to double gives a decimal answer.
  4. Lines 9 to 1095 plus a 14.25 tip is 109.25, and 109.25 divided by 4 is 27.3125.
  5. Line 11Math.Round keeps two decimal places for a price.
Example 2

Updating a score

C#

int score = 0;

score += 50;

score *= 2;

score -= 15;

score++;

Console.WriteLine($"Score: {score}");

int lives = 3;

int before = lives--;

Console.WriteLine($"{before} {lives}");

int minutes = 135;

Console.WriteLine($"{minutes / 60}h {minutes % 60}m");
Output

Score: 86

3 2

2h 15m
Line-by-line explanation
  1. Lines 2 to 50 + 50 = 50, doubled is 100, minus 15 is 85, plus one is 86.
  2. Line 9lives-- gives the old value, 3, and then decreases lives to 2.
  3. Line 13Integer division gives the hours and % gives the remaining minutes.
Example 3

Conditions and the Math class

C#

int age = 17;

bool hasPermission = true;

bool canJoin = age >= 18 || hasPermission;

Console.WriteLine(canJoin);

string? name = null;

bool valid = name != null && name.Length > 2;

Console.WriteLine(valid);

Console.WriteLine(Math.Pow(2, 8));

Console.WriteLine(Math.Sqrt(144));

Console.WriteLine(Math.Clamp(130, 0, 100));

Console.WriteLine(Math.Round(2.5));

Console.WriteLine(Math.Round(2.5, MidpointRounding.AwayFromZero));
Output

True

False

256

12

100

2

3
Line-by-line explanation
  1. Line 3|| is true because one side, hasPermission, is true.
  2. Line 7&& short-circuits: name is null, so name.Length is never evaluated and nothing crashes.
  3. Lines 10 to 11Pow and Sqrt return doubles; whole-number doubles print without a decimal point.
  4. Line 12Clamp limits 130 to the maximum of 100.
  5. Lines 13 to 14Default rounding sends 2.5 to the even number 2; AwayFromZero gives 3.

Common C# Basics Mistakes

Expecting a decimal from integer division

Don't

double average = 7 / 2;          // 3, because the division happens with ints
Do

double average = 7 / 2.0;        // 3.5

Using = instead of ==

Don't

if (count = 10) { }              // error CS0029: cannot convert int to bool
Do

if (count == 10) { }

Off-by-one with Random.Next

Don't

int dice = Random.Shared.Next(1, 6);   // only 1 to 5
Do

int dice = Random.Shared.Next(1, 7);   // 1 to 6

C# Basics in Real Projects

Operators in real code

Checkout code multiplies quantities by prices and applies discounts with decimal arithmetic. Pagination uses integer division and % to work out the number of pages and items on the last page. Games use Math.Clamp to keep health between 0 and 100, and Random.Shared for dice rolls and loot drops. Access rules combine conditions such as isAdmin || (isOwner && !isLocked).

C# Basics FAQ

Why does 7 / 2 equal 3 in C#?

When both operands are integers, / performs integer division and throws away the fraction. Make at least one operand a double or decimal, such as 7.0 / 2 or (double)a / b, to get 3.5. Casting the result instead, as in (double)(a / b), is too late because the fraction has already gone.

How do I round to 2 decimal places in C#?

Use Math.Round(value, 2). Remember that the default mode is banker's rounding, so pass MidpointRounding.AwayFromZero if you want halves to round up. If you only need two decimals for display, format the value instead with {value:F2} and keep the full number for calculations.

What is the difference between x++ and ++x?

Both add one to x. Used inside a larger expression, x++ gives the value from before the increment and ++x gives the value after it. When the statement is just x++; on its own line, there's no difference.

How do I calculate a power or square root in C#?

C# has no power operator, and ^ means exclusive-or, not "to the power of". Use Math.Pow(2, 10) for powers and Math.Sqrt(81) for square roots; both return a double. Cast the result with (int) if you need a whole number.

What is the difference between & and && in C#?

&& is the conditional "and": it skips the right-hand side when the left side is already false. & evaluates both sides every time, and on integers it performs a bitwise AND. For ordinary conditions use && and ||, so that checks like s != null && s.Length > 0 stay safe.

C# Basics Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Fill in the blankseasy

Complete the code to add 10 to points.


int points = 5;

points  10;
Predict the outputeasy

What does this print?


Console.WriteLine(17 % 5);
Predict the outputmedium

What does this print?


int x = 5;

int y = x++ + 1;

Console.WriteLine($"{x} {y}");
Multiple choicemedium

Why is name != null && name.Length > 0 safe when name is null?

Multiple choicehard

What does Math.Round(3.5) return by default?

C# Basics Quiz

5 questions to check what you learned.

  1. What is 10 / 4 in C# when both are ints?

    • 2.5
    • 3
    • 2
    • 2.0
  2. What does the || operator mean?

    • And
    • Not
    • Equal
    • Or
  3. What range does Random.Shared.Next(1, 11) return?

    • 0 to 10
    • 1 to 11
    • 0 to 11
    • 1 to 10
  4. What does Math.Clamp(-5, 0, 10) return?

    • -5
    • 0
    • 10
    • 5
  5. Which expression checks whether n is even?

    • n / 2 == 0
    • n % 2 == 1
    • n % 2 == 0
    • n == 2