Operators
Operators transform values: arithmetic for calculations, comparison for branching, logical for compound conditions, and assignment for state updates.
Introduction
Operators transform values: arithmetic for calculations, comparison for branching, logical for compound conditions, and assignment for state updates. C# also provides null-coalescing (??), null-conditional (?.), and pattern-matching operators that replace verbose null checks.
Interviewers probe operator precedence, short-circuit evaluation of && and ||, and the difference between == and ReferenceEquals. Misusing + for string building in hot paths or assigning with = inside conditions are classic junior mistakes.
This lesson maps every operator category with banking and validation examples you will reuse through LINQ and ASP.NET Core model binding.
The story
An e-commerce checkout page calculates tax, applies a promo code like SAVE10, and masks the customer's card number on the receipt. The payment service must combine arithmetic, null-safe defaults, and string slicing without crashing when optional fields are missing.
Operators and expressions are the glue between user input and the final charge amount shown on the confirmation screen.
Understanding the topic
Key concepts
- Arithmetic: + - * / % — integer division truncates; use cast or decimal for precision.
- Comparison: == != < > <= >= — structs may override Equals; classes default to reference equality.
- Logical: && || ! short-circuit; & | for bitwise; ^ XOR.
- Assignment: = += -= ?? ??= — null-coalescing assignment (C# 8+).
- Null-conditional ?. and ?[] safely navigate null references.
- is / is not pattern matching replaces type checks and casts.
flowchart LRA[Operands] --> Arith[+ - * /]A --> Compare[== != < >]A --> Logical[&& || !]Arith --> Result[Expression Result]
Step-by-step explanation
- Expressions evaluate left-to-right respecting precedence (multiplication before addition).
- Short-circuit: && skips right if left false; || skips if left true.
- ?? returns right operand when left is null.
- ?. returns null if receiver null instead of throwing.
- Compound assignment x += 1 reads and writes x atomically for primitives.
- Operator overloading allows custom types to use +, == with syntax sugar.
Practical code example
Null-coalescing, conditional access, and pattern matching in a payment validation helper:
namespace TechLearningPro.Operators;public static class PaymentValidator{public static decimal CalculateTotal(decimal? amount, decimal taxRate, string? promoCode){decimal baseAmount = amount ?? throw new ArgumentNullException(nameof(amount));decimal tax = baseAmount * taxRate;decimal discount = promoCode switch{"SAVE10" => baseAmount * 0.10m,"SAVE20" => baseAmount * 0.20m,null or "" => 0m,_ => 0m};return baseAmount + tax - discount;}public static string FormatCardLast4(string? cardToken) =>cardToken?.Length >= 4 ? quot;****{cardToken[^4..]}" : "N/A";}
Line-by-line code explanation
decimal? amountallows null when the cart total has not been computed yet.amount ?? throw new ArgumentNullException(...)uses the null-coalescing operator to fail fast on missing data.decimal tax = baseAmount * taxRateapplies standard arithmetic with decimal precision.promoCode switch { ... }is a switch expression that maps codes to discount amounts."SAVE10" => baseAmount * 0.10mcalculates a ten-percent discount for a known promo.null or "" => 0mhandles empty promo codes without throwing._ => 0mis the discard arm for unrecognized codes — safe default behavior.return baseAmount + tax - discountcombines subtotal, tax, and discount into the final total.cardToken?.Length >= 4uses null-conditional access before reading the token length.cardToken[^4..]takes the last four characters with the index-from-end range operator.
Key takeaway: Throw expression on ?? catches missing amounts early. Range operator [^4..] takes last four chars — C# 8+ index from end.
Real-world use
Where you'll use this in production
- Pricing engines combining discounts with null-safe promo codes.
- Healthcare eligibility rules with chained && conditions.
- API query filters building dynamic LINQ with null-coalesced defaults.
- Bitwise flags for feature toggles in enterprise licensing.
Best practices
- Use ?? and ?. instead of nested if-null checks.
- Parenthesize complex conditions for readability.
- Never assign in condition unless intentional (while ((x = Read()) != null)).
- Override Equals/GetHashCode together when comparing custom types.
- Use switch expressions for mapping discrete values.
Common mistakes
- Using & instead of && — no short-circuit, NullReferenceException risk.
- Integer division 5/2 equals 2 — need 5/2.0 or 5m/2m.
- Comparing strings with == without understanding interning vs ordinal.
- Overusing ++ in expressions harming readability.
Advanced interview questions
Q1BeginnerWhat is short-circuit evaluation?
Q2BeginnerDifference between == and Equals?
Q3IntermediateExplain ?? vs ?.
Q4IntermediateWhen overload operators?
Q5AdvancedHow does pattern matching with is improve on traditional casts?
Summary
C# operators cover arithmetic, logic, assignment, and null-safety. Short-circuit and precedence affect both correctness and performance. ?? ?. and switch expressions replace boilerplate null and branch code. Use decimal operators for financial math. Next: Console I/O and formatting user-facing output.