Welcome to this beginner's guide to operators and expressions in C#! Understanding these fundamental concepts is crucial for writing any kind of logic in your programs. They are the tools you use to manipulate data, make decisions, and control the flow of your applications.
Operators are special symbols that perform operations on one or more values (operands). Think of them as verbs in your programming language. C# provides a rich set of operators for various tasks.
These operators are used for mathematical calculations.
+
: Addition-
: Subtraction*
: Multiplication/
: Division%
: Modulus (returns the remainder of a division)
int a = 10;
int b = 3;
int sum = a + b; // sum will be 13
int difference = a - b; // difference will be 7
int product = a * b; // product will be 30
int quotient = a / b; // quotient will be 3 (integer division)
int remainder = a % b; // remainder will be 1
Console.WriteLine($"Sum: {sum}");
Console.WriteLine($"Difference: {difference}");
Console.WriteLine($"Product: {product}");
Console.WriteLine($"Quotient: {quotient}");
Console.WriteLine($"Remainder: {remainder}");
These operators assign values to variables. The most basic is the assignment operator =
.
=
: Assigns a value.+=
: Adds and assigns. (e.g., x += 5
is the same as x = x + 5
)-=
: Subtracts and assigns.*=
: Multiplies and assigns./=
: Divides and assigns.%=
: Modulus and assigns.
int count = 10;
count += 5; // count is now 15
count *= 2; // count is now 30
These operators compare two values and return a boolean result (true
or false
).
==
: Equal to!=
: Not equal to>
: Greater than<
: Less than>=
: Greater than or equal to<=
: Less than or equal to
int score = 85;
bool isPassing = score >= 60; // isPassing will be true
bool isExcellent = score > 90; // isExcellent will be false
Console.WriteLine($"Is passing? {isPassing}");
Console.WriteLine($"Is excellent? {isExcellent}");
These operators combine or modify boolean expressions.
&&
: Logical AND (returns true if both operands are true)||
: Logical OR (returns true if at least one operand is true)!
: Logical NOT (reverses the boolean value)
bool hasLicense = true;
bool hasCar = false;
bool canDrive = hasLicense && hasCar; // canDrive will be false
bool canTravel = hasLicense || hasCar; // canTravel will be true
bool isNotLicensed = !hasLicense; // isNotLicensed will be false
Console.WriteLine($"Can drive? {canDrive}");
Console.WriteLine($"Can travel? {canTravel}");
Console.WriteLine($"Is not licensed? {isNotLicensed}");
These are shorthand for increasing or decreasing a variable's value by 1.
++
: Increment (e.g., x++
or ++x
)--
: Decrement (e.g., x--
or --x
)Note the difference between pre-increment/decrement (++x
) and post-increment/decrement (x++
). Pre-increment/decrement modifies the variable *before* its value is used in the expression, while post-increment/decrement uses the variable's *current* value and then modifies it.
int x = 5;
Console.WriteLine($"Initial x: {x}"); // Output: 5
int y = ++x; // x becomes 6, then y is assigned 6
Console.WriteLine($"After ++x, x: {x}, y: {y}"); // Output: After ++x, x: 6, y: 6
x = 5; // Reset x
int z = x++; // y is assigned 5, then x becomes 6
Console.WriteLine($"After x++, x: {x}, z: {z}"); // Output: After x++, x: 6, z: 5
? :
: Ternary Conditional Operator (a shorthand for if-else).
: Member Access Operator (to access members of an object or type)[]
: Indexer Operator (to access elements of arrays or collections)new
: Creates a new objecttypeof
: Returns the Type object of a typeis
: Checks if an object is compatible with a given typeas
: Casts an object to a given type, returns null if cast failsAn expression is a combination of operators, operands, and method calls that evaluates to a single value. Every statement in C# must contain at least one expression.
5 + 3
(evaluates to 8)userName.Length
(evaluates to the length of the string in userName
)isReady == true
(evaluates to true
or false
)GetDiscount(price) > 10
(evaluates to true
or false
)Key Takeaway: Operators are the symbols that do the work, and expressions are the combinations that produce a result. Together, they form the fundamental language for manipulating data and controlling program logic.
When an expression contains multiple operators, C# follows a set of rules to determine the order of evaluation:
++
, --
, !
) are often right-associative.You can use parentheses ()
to explicitly control the order of evaluation and override default precedence rules. This often makes your code clearer and less prone to errors.
// Without parentheses, multiplication happens first
int result1 = 5 + 2 * 3; // 5 + 6 = 11
// With parentheses, addition happens first
int result2 = (5 + 2) * 3; // 7 * 3 = 21
Console.WriteLine($"Result 1: {result1}");
Console.WriteLine($"Result 2: {result2}");
Operators and expressions are the bedrock of C# programming. By mastering their usage and understanding precedence, you'll be well on your way to writing powerful and efficient code. Keep practicing, and don't hesitate to experiment with different combinations!
Continue your learning journey with more advanced C# topics or explore other programming languages.