skip to content

Syntax and Statements

Top-level programs, namespaces, var and const, operators and casts, numeric types and loops: the grammar every C# answer is written in. Interviewers open here.

on this pageshow

explore

questions

28

In C#, how do for, foreach, while and do-while differ in when they test their condition and where their loop variables live?

level: juniorimportance: must knowfreq 70%

answer

  1. zero runs versus at least one
  2. condition checked before or after the body
  3. body block ends before the do condition
  4. foreach variable is read-only

basics

~20 s

for and while test their condition before each pass and may run zero times; do-while tests after the body, so it runs at least once. foreach visits elements through a read-only variable, and loop variables stay inside the loop.

solid answer

~50 s

`while` and `for` evaluate a `bool` condition before every pass, so the body can run zero times; `do { } while (cond);` evaluates it after the body, so the body runs at least once, which suits a sensor read you must attempt before you can judge it. `for` packs an initializer, a condition and an iterator into one header, and a variable declared in that initializer is gone after the loop (CS0103 if you read it later). `foreach` walks a collection; its iteration variable is read-only, so assigning to it is CS1656, though you can still change the members of the object it refers to. One C# trap: a local declared inside a `do` body is out of scope in the `while` condition, so the variable the condition tests must be declared before the `do`.

code

csharp · 23 lines
csharp
int? reading;
int attempt = 0;

do
{
    attempt++;
    reading = ReadGateSensor(attempt);
    Console.WriteLine($"attempt {attempt}: {(reading == null ? "no echo" : reading + " cm")}");
}
while (reading == null && attempt < 3);

string[] lanes = ["entry", "exit"];
foreach (string lane in lanes)
{
    Console.WriteLine($"lane {lane} checked");
}

for (int i = 0; i < lanes.Length; i++)
{
    Console.WriteLine($"lane {i}: {lanes[i]}");
}

static int? ReadGateSensor(int attempt) => attempt < 2 ? null : 140;

go deeper

for a junior

Recall that do-while is the only loop guaranteed to run once, and that for and foreach variables disappear after the loop. Know CS1656 by its meaning: the foreach variable is read-only.

for a middle

Explain the scope rules behind the errors: the do body block closes before the condition, the for initializer is scoped to the statement, and C# conditions must be bool with no int-to-bool conversion.

for a senior

Pick the loop that states intent in review: a bounded retry as do-while or for with break, not while (true) with scattered exits, and explain why foreach cannot write elements back.

for a principal

There is little to decide at lead level here; the value is in review norms, such as preferring bounded loops for retries and index loops only when the index is genuinely needed.

C# has four **iteration statements**: `for`, `foreach`, `while` and `do`. They differ in two ways an interviewer probes: *when* the loop condition is evaluated, and *where* the variables the loop introduces are visible. Both are decided by the compiler, so getting them wrong produces a CS-numbered error rather than a subtle bug. ## When each loop tests its condition | statement | condition tested | minimum passes | natural fit | |---|---|---|---| | `while (cond) body` | before each pass | 0 | repeat while something stays true | | `for (init; cond; iter) body` | before each pass | 0 | a counter or index over a known range | | `do body while (cond);` | after each pass | 1 | act first, then decide whether to repeat | | `foreach (T x in source) body` | before each element | 0 | visit every element of a collection | - The **condition must be a `bool`**. C# has no implicit conversion from `int` to `bool`, so `while (count)` fails with CS0029, "Cannot implicitly convert type 'int' to 'bool'". - Every section of a `for` header is optional; `for (;;)` with no condition loops until a jump statement such as `break` or `return`, or an exception, leaves it. - A `do` statement ends with a semicolon after the `while (...)` clause; it is the only loop whose body always executes at least once. - `foreach` over an empty collection skips the body; `foreach` over a `null` reference throws `NullReferenceException`. ## Where loop variables live The scope rules are what separates someone who has written C# from someone who has read about loops. 1. **A `for` initializer variable** is scoped to the whole `for` statement: the condition, the iterator and the body can use it, the code after the loop cannot. Reading `i` after `for (int i = 0; ...)` is CS0103, "The name 'i' does not exist in the current context". Two loops in a row may each declare their own `i`. 2. **A local declared inside a `do` body** belongs to the body's block, and that block closes before `while (...)` is evaluated. Writing `do { int? reading = Read(); } while (reading == null);` is CS0103 on `reading`. Declare the variable before `do` and assign it inside. 3. **The `foreach` iteration variable** is a read-only local. `lane = lane.Trim();` inside `foreach (string lane in lanes)` is CS1656, "Cannot assign to 'lane' because it is a 'foreach iteration variable'". Mutating the object it refers to (setting a property on a class instance) is allowed; replacing the element needs an index-based loop. ## Choosing a loop: a retry with a fixed budget A parking-garage barrier controller reads an ultrasonic sensor that sometimes returns no echo, and may retry up to three times. Three shapes are correct: - **`do`/`while` with a counter**: read, then test `reading == null && attempt < 3`. The read always happens once, which matches the requirement, and both variables live outside the body so the condition can see them. - **`for` with `break`**: `for (int attempt = 1; attempt <= 3; attempt++) { reading = Read(); if (reading != null) break; }`. The attempt counter stays scoped to the loop; the result variable must be declared before it. - **`while (true)` with `break`**: legal and common, but the exit conditions are scattered through the body; reviewers usually prefer the bounded form. `foreach` is the wrong tool for a retry, because there is no collection to walk; it is the right tool for checking every lane in a `string[]` of lane names, where an index adds nothing. Choose `for` over `foreach` when you need the index itself, need to step by more than one, or need to write elements back. ## What these loops have in common - `break` leaves the nearest enclosing loop (or `switch`), and `continue` jumps to the next evaluation of the nearest loop's condition (for a `for`, after running the iterator section). - `return` leaves the whole method, loop included. - None of the four loops leaks its own variables to the code after it, so a value the loop computes must be held in a variable declared before the loop. ## Neighbouring material How `foreach` finds a `GetEnumerator` method, and why it works on `Span<T>` without any interface, is covered with the enumerator contract. Why lambdas created in a `for` loop all see the final counter while a `foreach` loop gives each its own variable is covered with lambdas and closures. `await foreach` belongs with asynchronous streams.

  • In C#, can a foreach loop change the elements of a List<Ticket> it is iterating?
    It cannot assign the iteration variable (CS1656), so it cannot replace an element. If `Ticket` is a class, setting `ticket.Paid = true` changes the shared object and is fine. Replacing elements needs a `for` loop with the indexer, and even `list[i] = x` inside a `foreach` over that same list throws `InvalidOperationException`, because the indexer's setter counts as modifying the list.
  • In a C# for loop, when does continue run the iterator section?
    `continue` skips the rest of the body and goes to the iterator section, then the condition. So in `for (int i = 0; i < n; i++)` a `continue` still increments `i`. In a `while` loop the increment is part of the body, so a `continue` placed before it skips it and can loop forever, a classic bug when a `for` is rewritten as a `while`.

  • Says a C# while loop always runs its body at least once.
  • Thinks a variable declared inside a do body is visible in its while condition.
  • Believes a for loop counter is still readable after the loop ends.
  • Thinks while (count) works for a nonzero int, as a truthiness test.
  • Believes the foreach iteration variable can be reassigned to replace the element.
open as a page

In C#, what do the int expressions -1000 / 3 and -1000 % 3 evaluate to, and how do you keep the fraction?

level: juniorimportance: must knowfreq 72%

basics

~20 s

With two int operands C# divides as integers and truncates toward zero: -1000 / 3 is -333 and -1000 % 3 is -1. Convert an operand to double or decimal before dividing to keep the fraction.

open as a page

In C#, when does an explicit cast like `(TemperatureReading)item` throw, and when does `item as TemperatureReading` return null instead?

level: juniorimportance: must knowfreq 72%

basics

~20 s

A cast (T)x throws InvalidCastException when the object's run-time type is incompatible with T, while x as T returns null. For a class target, null passes through both; as needs a reference or nullable target and never runs user-defined conversions.

open as a page

In C#, what does the compiler generate for a Program.cs written with top-level statements, and how do args, await and return shape it?

level: juniorimportance: must knowfreq 68%

basics

~20 s

The compiler wraps the statements in a generated static entry-point method of a partial class Program in the global namespace. args is its string[] parameter; await makes it return Task, a returned value makes it int, and both give Task<int>.

open as a page

In C#, is a local declared with var dynamically typed, and where does the compiler refuse to accept var?

level: juniorimportance: must knowfreq 75%

basics

~20 s

A var local is statically typed: the compiler infers one fixed type from the initializer, exactly as if you had written it. var works only on initialized locals; fields, null initializers, multiple declarators and bare array initializers are rejected.

open as a page

In C#, why does removing items from a List<T> inside a foreach over that list throw, and which loop rewrites are safe?

level: middleimportance: must knowfreq 60%

basics

~10 s

List<T>'s enumerator detects any change to the list and the next step of foreach throws InvalidOperationException. Remove with a backward for loop and RemoveAt, call RemoveAll with a predicate, or loop over a copy.

open as a page

Why does a C# switch statement reject one case section running into the next, and how do stacked labels and goto case replace fall-through?

level: middleimportance: must knowfreq 60%

basics

~20 s

C# requires the end of every switch section to be unreachable, so implicit fall-through is a compile error (CS0163). Several case labels may share one section, and goto case or goto default jumps to another section explicitly.

open as a page

In C#, why does incrementing an int counter at int.MaxValue wrap silently while int.MaxValue + 1 fails to compile, and what does checked change?

level: middleimportance: must knowfreq 62%

basics

~20 s

Non-constant integer arithmetic in C# runs unchecked by default, so int.MaxValue + 1 silently wraps. Constant expressions are checked by default, giving CS0220. A checked expression or block throws OverflowException instead; unchecked opts back into wrapping.

open as a page

In a C# invoicing service, why should line totals and tax be decimal rather than double, and what can decimal still get wrong?

level: middleimportance: must knowfreq 78%

basics

~20 s

decimal stores a base-10 scaled integer, so 0.10 and 0.20 add to exactly 0.30, while double's binary fractions cannot represent 0.1. decimal still rounds non-terminating results like 1m / 3m, and costs 16 bytes and software arithmetic.

open as a page

In C#, how do const and static readonly fields differ, and why does a changed public const in a shared library not reach compiled callers?

level: middleimportance: must knowfreq 70%

basics

~20 s

A const is a compile-time value copied into every caller's IL, so callers keep the old value until they are recompiled. A static readonly field is read from its assembly at run time, may have any type and is assigned once.

open as a page

In C#, why does reading a local assigned only inside an if fail with CS0165, while an unassigned field reads as zero?

level: juniorimportance: should knowfreq 45%

basics

~20 s

C# requires every local to be definitely assigned on every path before it is read, and CS0165 reports any path that skips the assignment. Fields and array elements start zeroed when their memory is created, so they need no such proof.

open as a page

In a C# command loop that switches on each command, why does break in the quit case not stop the loop, and what does?

level: middleimportance: should knowfreq 45%

basics

~20 s

C# break leaves the nearest enclosing switch or loop, which inside a switch section is the switch, so the loop continues. Stop the loop with return from a method, a flag the loop condition tests, or goto a label.

open as a page

In C#, why does Math.Round(2.5) return 2, and how should an invoicing service round a tax amount to cents?

level: middleimportance: should knowfreq 55%

basics

~20 s

Math.Round uses MidpointRounding.ToEven by default, so a value exactly halfway goes to the even neighbour: 2.5 becomes 2 and 3.5 becomes 4. For cents, round a decimal with Math.Round(amount, 2, mode) and name the mode explicitly.

open as a page

In C#, why does adding two bytes into a byte fail to compile, while assigning an int to a float compiles but may round?

level: middleimportance: should knowfreq 52%

basics

~20 s

C# adds two bytes as int, and int to byte is an explicit narrowing conversion, so CS0266 demands a cast. int to float is implicit because it never loses magnitude, but a float cannot hold every integer above 16,777,216.

open as a page

In a C# units-of-measure library, when should a Celsius conversion operator be implicit rather than explicit, and which declarations does the compiler reject?

level: middleimportance: should knowfreq 45%

basics

~20 s

Make a conversion operator implicit only when it can never throw or lose information; otherwise make it explicit so callers must cast. It must be public static, involve the enclosing type, and avoid interface, base, derived or same-type conversions.

open as a page

In C# 10 and later, what does a file-scoped namespace declaration change, and which placements in a file does the compiler reject?

level: middleimportance: should knowfreq 40%

basics

~20 s

namespace MigrationTool; places every type in the file in that namespace without braces, like a block namespace around the rest of the file. A file gets one, cannot mix it with block namespaces, and must declare it before any type or statement.

open as a page

In C# 10 and later, what do global using directives and the SDK's ImplicitUsings setting do, and why can they cause CS0104 errors?

level: middleimportance: should knowfreq 45%

basics

~20 s

A global using applies one using directive to every file in the compilation, and ImplicitUsings makes the .NET SDK generate such directives for common namespaces like System. More imports mean more simple names, so same-named types turn ambiguous (CS0104).

open as a page

Which static Main signatures does the C# compiler accept as a program's entry point, and what changes when Main is async Task<int>?

level: middleimportance: should knowfreq 50%

basics

~20 s

A C# entry point is a static Main returning void, int, Task or Task<int>, taking nothing or one string[]. async is legal only on the task forms, and the compiler then adds a bridge that waits and returns the int as the exit code.

open as a page

Why does C#'s `int? bonus = missing ? default : 5;` store 0 instead of null, and when do default and new() need a target?

level: middleimportance: should knowfreq 40%

basics

~20 s

In missing ? default : 5, the int branch gives the conditional the natural type int, so default becomes 0 before the conversion to int?. The default literal and new() need a target type and fail without one, as with var.

open as a page

In C#, what type does a conditional expression like flag ? 1 : null get, and why can it not be a statement?

level: seniorimportance: should knowfreq 30%

basics

~20 s

A C# conditional expression takes its operands' common type; without one, C# 9 and later convert each operand to the target type, so int? x = flag ? 1 : null compiles and var does not. It cannot be a statement (CS0201).

open as a page

In C#, why is `rate == double.NaN` always false for a double rate, yet `List<double>.Contains(double.NaN)` can find a NaN?

level: seniorimportance: should knowfreq 40%

basics

~10 s

The == operator follows IEEE 754, where NaN is unequal to everything, itself included. double.Equals(double) treats two NaNs as equal, and List<double>.Contains compares with Equals, so it finds them. Test with double.IsNaN.

open as a page

When overloading operators on a C# struct such as Celsius, which operators must come in pairs, which cannot be overloaded, and how does && still work?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Operators are public static members taking the declaring type; ==/!=, </>, <=/>= and true/false must be paired (CS0216). =, &&, ||, ?:, the cast (T)x and a[i] cannot be overloaded; && and || come from & or | plus operator true and false.

open as a page

A C# class Migration sits in namespace MigrationTool.Migration; why does new Migration() compile in the top-level Program.cs but fail with CS0118 inside namespace MigrationTool?

level: seniorimportance: should knowfreq 30%

basics

~20 s

C# resolves a simple name from the innermost namespace outward, checking each namespace's own members before its using directives. Inside MigrationTool, Migration first matches the namespace MigrationTool.Migration, giving CS0118; the global namespace has no such member, so Program.cs reaches the using.

open as a page

A C# payroll import reads rows as dynamic, and a misspelled row.Salry compiles but throws; how do dynamic, var and object differ?

level: seniorimportance: should knowfreq 45%

basics

~20 s

var is a compile-time inferred type and object is a static type exposing only object's members; the compiler checks both. dynamic skips compile-time checking: each operation is bound at run time on the actual type, so a typo throws RuntimeBinderException.

open as a page

As the lead of a C# codebase, would you store money as decimal or as long minor units, and would you turn on CheckForOverflowUnderflow?

level: principalimportance: should knowfreq 30%

basics

~20 s

Most C# business code should use decimal for money, keeping long minor units for hot paths or storage formats that demand integers. Turning on CheckForOverflowUnderflow, at least in test builds, catches silent integer wrap; deliberate wrapping then needs unchecked.

open as a page

In C#, what do using static and using alias directives bring into scope, and which types can a C# 12 using alias name?

level: middleimportance: nice to knowfreq 28%

basics

~20 s

using static imports one type's static members and nested types; a using alias gives a namespace or type a second name. Since C# 12 an alias can name any type, such as a tuple or array, but never a nullable reference type.

open as a page

In C#, when is `_` a discard and when is it an ordinary variable, as in `_ = SendAuditAsync();` versus `var _ = SendAuditAsync();`?

level: middleimportance: nice to knowfreq 30%

basics

~20 s

In C#, _ is a discard only when no variable named _ is in scope: _ = expr;, out _, or several _ lambda parameters. var _ = expr; declares an ordinary local named _ instead.

open as a page

In C# 14, what changes when a class declares `public void operator +=(double reading)` instead of relying on its static `operator +` for `stats += reading`?

level: seniorimportance: nice to knowfreq 15%

basics

~20 s

Without it, stats += reading compiles to stats = stats + reading, creating a new object. A C# 14 instance operator += mutates the object in place, so every alias sees the change; property targets still use the static operator.

open as a page