C# Operators and Expressions

Table of Contents

Arithmetic Operators

C# provides a set of arithmetic operators for performing mathematical operations on numeric values.

int x = 10; int y = 5; int sum = x + y; // Addition int difference = x - y; // Subtraction int product = x * y; // Multiplication int quotient = x / y; // Division int remainder = x % y; // Modulus

Assignment Operators

Assignment operators are used to assign values to variables.

int x = 10; x += 5; // Equivalent to x = x + 5; x -= 3; // Equivalent to x = x - 3; x *= 2; // Equivalent to x = x * 2; x /= 3; // Equivalent to x = x / 3; x %= 4; // Equivalent to x = x % 4;

Comparison Operators

Comparison operators are used to compare two values.

int x = 10; int y = 5; bool isEqual = (x == y); // False bool greaterThan = (x > y); // True bool lessThan = (x < y); // True bool greaterThanOrEqual = (x >= y); // True bool lessThanOrEqual = (x <= y); // True

Logical Operators

Logical operators are used to combine or negate boolean expressions.

bool a = true; bool b = false; bool result = (a && b); // False result = (a || b); // True result = !(a && b); // True

Bitwise Operators

Bitwise operators perform operations on individual bits of numeric values.

int x = 10; // Binary: 1010 int y = 4; // Binary: 0100 int andResult = x & y; // Binary: 0000 int orResult = x | y; // Binary: 1110 int xorResult = x ^ y; // Binary: 1110 int notResult = ~x; // Binary: ...11111111111111111111111111111011

Compound Assignment Operators

Compound assignment operators combine an arithmetic or bitwise operator with an assignment operator.

int x = 10; x += 5; // Equivalent to x = x + 5; x -= 5; // Equivalent to x = x - 5; x *= 5; // Equivalent to x = x * 5; x /= 5; // Equivalent to x = x / 5; x %= 5; // Equivalent to x = x % 5;

Type Conversion

C# provides several ways to convert between different numeric types.

double d = 10.5; int i = (int)d; // Cast to int. Truncates the decimal part. double d2 = i; // Cast to double.

Expression Evaluation

C# evaluates expressions in a specific order of precedence.

int x = 10; int y = 5; int z = x + y * 2; // Multiplication is evaluated before addition.