Operators are the action verbs of a programming language. They take variables and values, perform operations on them, and produce results. Just as a calculator uses + and -, C# provides a rich set of operators for mathematics, logic, and data manipulation.
Important Note on Division: If you divide two integers, C# truncates the decimal. 5 / 2 results in 2. To get 2.5, at least one number must be a double: 5.0 / 2.
A very powerful operator in C#. It returns the left-hand operand if it is NOT null; otherwise, it returns the right-hand operand.
csharp
1234567
string defaultName = "Guest";
string userName = null; // Imagine this came from an empty database field// If userName is null, use defaultName instead
string displayName = userName ?? defaultName;
Console.WriteLine(displayName); // Prints "Guest"
*(Note: C# 8.0 introduced the ??= operator, which assigns the right value to the left variable ONLY if the left variable is currently null).*
Always use parentheses () when combining multiple logical operators to make the order of operations explicitly clear. Example: if ((age > 18) && (hasLicense == true))
Operators are the backbone of program logic. Arithmetic operators handle math, relational operators compare values, and logical operators combine conditions. The ternary and null-coalescing operators are C# shortcuts that make your code cleaner and more professional.
In Chapter 6: User Input and Output, we will make our programs interactive by learning how to ask the user for data using Console.ReadLine() and format output beautifully.
Finish this Chapter
Save your progress on your learning path and prepare for coding interview challenges.