Roadmap › C# Language — Basics to Advanced › Module: Getting Started
Lessons in this course (38)
5. Variables, constants and operators
Basic★ Must knowLesson 5 of 38
csharp
int age = 30; // declare + initialise; a local must be assigned before use
var city = "Pune"; // type inferred at compile time — still strongly typed (city is string)
const double Pi = 3.14159; // compile-time constant
// readonly DateTime created; // (field only) set once, in declaration or constructor
int a = 10, b = 3; // several variables in one statementScope: a variable exists inside the { } block where it is declared; locals are not visible outside their method, loop or if block.
| Category | Operators | Example |
|---|---|---|
| Arithmetic | + - * / % ++ -- | a % b → 1; i++ (use then add) vs ++i (add then use) |
| Assignment | = += -= *= /= %= ??= | total += price; |
| Comparison | == != > < >= <= | age >= 18 |
| Logical | && || ! (short-circuit), & | (always evaluate both) | isAdmin || isOwner |
| Bitwise | & | ^ ~ << >> | flags & Perm.Write |
| Null | ?. ?[] ?? ??= ! | name?.Length ?? 0 |
| Type | is, as, typeof, sizeof, nameof | obj is string s |
| Conditional | ? : | age >= 18 ? "adult" : "minor" |
| Range / index | .. ^ | arr[^1] last item, arr[1..3] |
| Lambda | => | x => x * 2 |
csharp
int i = 5;
Console.WriteLine(i++); // 5 (then i = 6)
Console.WriteLine(++i); // 7
string? s = null;
int len = s?.Length ?? 0; // null-conditional + null-coalescing
s ??= "default"; // assign only if null
Console.WriteLine(2 + 3 * 4); // 14 — * before + (precedence)
Console.WriteLine((2 + 3) * 4); // 20 — use brackets to make intent clear==compares values for value types and references for reference types unless overloaded (stringoverloads it to compare text; records compare values).&&and||short-circuit:if (user != null && user.IsActive)never touchesuserwhen it is null.ischecks type/pattern;ascasts and returnsnullon failure instead of throwing.