C# quiz – 40 questions with answers
Try it interactively
With scoring, random questions, and saved progress – or go straight to the timed exam with certificate.
Beginner (14 questions)
How do you print a line of text to the console in C#?
- Console.Print("Hi");
- Console.WriteLine("Hi");
- System.out.println("Hi");
- print("Hi")
Show answer
Correct: Console.WriteLine("Hi");
Console.WriteLine prints text with a line break; Console.Write without one.
What does 7 / 2 evaluate to when both numbers are int?
- 3.5
- 3
- 4
- 2
Show answer
Correct: 3
Integer division truncates the decimal places: 3. To get 3.5, at least one operand must be a double.
What does -7 % 3 evaluate to in C#?
- 2
- 1
- -1
- -2
Show answer
Correct: -1
The remainder has the sign of the dividend: -7 = (-2)·3 + (-1). So -1 (unlike in Python, where you get 2).
Which type do you use for monetary amounts?
- float
- double
- int
- decimal
Show answer
Correct: decimal
decimal calculates exactly in decimal (e.g. 0.1m + 0.2m == 0.3m); float/double have binary rounding errors.
What does this code print?
int x = 5;
x += 3;
Console.WriteLine(x);- 5
- 3
- 53
- 8
Show answer
Correct: 8
x += 3 is equivalent to x = x + 3, so 8.
What does var zahl = 42; mean?
- A dynamic type like in JavaScript
- The compiler infers
int; the type stays fixed zahlhas the typeobject- Error – a type must be specified
Show answer
Correct: The compiler infers int; the type stays fixed
var is compile-time type inference: zahl is an int and stays one.
What does this code print?
string name = "Ada";
int alter = 36;
Console.WriteLine($"{name} is {alter + 1}");- Ada is 36
- Ada is 37
- Ada is {alter + 1}
- Ada is alter + 1
Show answer
Correct: Ada is 37
Inside $"...", the { } may contain arbitrary expressions – here alter + 1 = 37.
How do you access the last element of the array a?
- a[-1]
- a[^1]
- a[last]
- a.Last
Show answer
Correct: a[^1]
The index-from-end operator ^1 denotes the last element (a[-1] does not exist in C#).
What does this code print?
for (int i = 0; i < 3; i++)
Console.Write(i);- 012
- 123
- 0123
- 210
Show answer
Correct: 012
i runs from 0 to 2 (i < 3); Write appends without a line break: 012.
Which keyword declares a constant?
- final
- let
- const
- static
Show answer
Correct: const
const int Max = 100; – the value is fixed at compile time.
What does int.TryParse("abc", out int n) return?
- Throws a
FormatException - Returns
false;nis 0 - Returns
null - Returns
true;nis 0
Show answer
Correct: Returns false; n is 0
TryParse does not throw an exception but reports failure via false; the out value is then the default value 0.
Which statement about a program from .NET 6 onwards is true?
- It always needs
class Programandstatic void Main - A single line
Console.WriteLine("Hi");is enough (top-level statements) - It needs a header file
- The method must be called
main(lowercase)
Show answer
Correct: A single line Console.WriteLine("Hi"); is enough (top-level statements)
Since C# 9 there are top-level statements: the compiler generates Program and Main itself.
What does this code print?
Console.WriteLine(10 > 5 ? "yes" : "no");- no
- yes
- True
- Error
Show answer
Correct: yes
The ternary operator picks the first value when the condition is true: "yes".
Which loop iterates directly over all elements of a list, without an index?
- for
- foreach
- while
- loop
Show answer
Correct: foreach
foreach (var x in liste) iterates over every element.
Intermediate (14 questions)
What does this code print?
var zahlen = new[] { 5, 3, 8, 1 };
Console.WriteLine(string.Join(",", zahlen.Where(z => z > 2).Select(z => z * 2)));- 10,6,16
- 5,3,8
- 10,16
- 6,10,16
Show answer
Correct: 10,6,16
Where keeps 5, 3, 8 (the order stays), Select doubles them: 10,6,16.
What output is produced?
var liste = new List<int> { 1, 2, 3 };
var abfrage = liste.Where(x => x > 1);
liste.Add(10);
Console.WriteLine(abfrage.Count());- 2
- 3
- 4
- Error
Show answer
Correct: 3
LINQ queries are executed lazily: Count() only runs now and sees 2, 3 and 10.
What does this code print?
var a = new Punkt(1, 2);
var b = new Punkt(1, 2);
Console.WriteLine(a == b);
record Punkt(int X, int Y);- True
- False
- Compiler error
- Depends on the memory addresses
Show answer
Correct: True
Records have value-based equality: identical contents mean ==. With a normal class it would be False.
What does the ?? operator do?
- Checks whether two values are equal
- Returns the left value if it is not null, otherwise the right one
- Throws an exception on null
- Converts to a nullable type
Show answer
Correct: Returns the left value if it is not null, otherwise the right one
a ?? b yields a if a is not null, otherwise b.
What does this code print?
string? s = null;
Console.WriteLine(s?.Length ?? -1);- 0
- -1
- Empty line
- NullReferenceException
Show answer
Correct: -1
s?.Length simply yields null for null (no crash), and ?? -1 then provides the fallback value -1.
What is the output of the code?
try { Console.Write("A"); throw new Exception(); }
catch { Console.Write("B"); }
finally { Console.Write("C"); }
Console.Write("D");- ACBD
- ABCD
- ACD
- ABC
Show answer
Correct: ABCD
A is written, the exception is caught (B), finally always runs (C), then execution continues normally (D).
What distinguishes a record from a normal class?
- Records are always value types
- Records have value-based equality, ToString and
withcopies built in - Records cannot be inherited
- Records have no methods
Show answer
Correct: Records have value-based equality, ToString and with copies built in
Records (reference types) offer value-based equality, a readable ToString output and with for non-destructive copies.
What does this code print?
var a = new List<int> { 1, 2 };
var b = a;
b.Add(3);
Console.WriteLine(a.Count);- 2
- 3
- 1
- Error
Show answer
Correct: 3
List<int> is a reference type: b = a only copies the reference, and both variables point to the same list.
What does using var datei = new StreamReader(pfad); do?
- Imports a namespace
Dispose()is called automatically at the end of the enclosing block- The file stays open until the program ends
- The file is deleted immediately
Show answer
Correct: Dispose() is called automatically at the end of the enclosing block
using guarantees that the resource is released, even when an exception occurs.
What is the difference between throw; and throw e; in a catch block?
- No difference
throw;keeps the original stack trace,throw e;overwrites itthrow;finally swallows the exceptionthrow e;is faster
Show answer
Correct: throw; keeps the original stack trace, throw e; overwrites it
With throw; the exception is passed on unchanged; throw e; resets the stack trace at this point and makes debugging harder.
What does this code print?
int n = 15;
string s = n switch { < 10 => "small", < 20 => "medium", _ => "large" };
Console.WriteLine(s);- small
- medium
- large
- Compiler error
Show answer
Correct: medium
The arms are checked in order: 15 is not < 10, but it is < 20 – so "medium".
What does this code print?
var d = new Dictionary<string, int> { ["a"] = 1 };
d["b"] = 2;
d["a"] += 10;
Console.WriteLine(d["a"] + d.Count);- 13
- 12
- 11
- Error
Show answer
Correct: 13
d["a"] is 1 + 10 = 11, d.Count is 2 – sum 13.
What happens with d["x"] if the key is missing from the dictionary?
nullis returned0is returned- A
KeyNotFoundExceptionis thrown - The key is created automatically
Show answer
Correct: A KeyNotFoundException is thrown
The indexer throws when the key is missing; use TryGetValue or GetValueOrDefault.
What does this code print?
object o = 42;
Console.WriteLine(o is int n && n > 40);- True
- False
- 42
- Compiler error
Show answer
Correct: True
The type pattern is int n tests and binds at the same time; n > 40 is true.
Advanced (12 questions)
What does await do in an async method?
- The thread is blocked until the task is finished
- The method pauses; the thread is freed and the method continues later
- It automatically starts a new thread per call
- It makes the code synchronous
Show answer
Correct: The method pauses; the thread is freed and the method continues later
await returns control until the operation has completed – meanwhile the thread can do other work.
Three tasks, each with Task.Delay(1000), are started and awaited with await Task.WhenAll(...). About how long does that take?
- 3 seconds
- 1 second
- 0 seconds
- They run one after another
Show answer
Correct: 1 second
Task.Delay does not block a thread; all three wait at the same time, and the total duration equals the longest task (about 1 s).
Why should you avoid .Result or .Wait() on a task?
- The methods no longer exist
- They can block threads and cause deadlocks
- They always return null
- They are slower than
await, but harmless
Show answer
Correct: They can block threads and cause deadlocks
Waiting synchronously on a task blocks a thread that the continuation may need – risk of deadlock (UI, ASP.NET contexts).
What is async void useful for?
- For all methods without a return value
- Only for event handlers
- For constructors
- For static methods
Show answer
Correct: Only for event handlers
With async void, the caller can neither wait nor catch exceptions. Otherwise always use async Task.
What output does this code produce?
var e = Zahlen();
Console.Write("X");
foreach (var z in e) Console.Write(z);
static IEnumerable<int> Zahlen()
{
Console.Write("A");
yield return 1;
Console.Write("B");
yield return 2;
}- AB12X
- XA1B2
- A1B2X
- XAB12
Show answer
Correct: XA1B2
Iterators run lazily: nothing happens at the call (X), only the foreach drives them: A, then 1, then B, then 2.
What does this code print?
var a = new P { X = 1 };
var b = a;
b.X = 5;
Console.WriteLine(a.X);
struct P { public int X; }- 5
- 1
- 0
- Compiler error
Show answer
Correct: 1
P is a struct (value type): b = a copies the whole value. Changes to b do not affect a. With a class it would be 5.
What does where T : class, new() mean?
- T must be a value type with a default value
- T must be a reference type with a parameterless constructor
- T must inherit from a class named
new - T can be anything
Show answer
Correct: T must be a reference type with a parameterless constructor
class restricts to reference types, new() requires a public parameterless constructor (so that new T() is allowed).
What is Span<T> used for?
- For sorting lists
- As a view over contiguous memory without copying and without heap allocation
- As a replacement for threads
- For time intervals
Show answer
Correct: As a view over contiguous memory without copying and without heap allocation
Span<T> points to a memory region (array, string, stack) and allows slicing without copying – useful for fast parsers.
What is important about primary constructors (C# 12) in normal classes?
- The parameters automatically become public properties
- The parameters are available in the class body but do not automatically become properties
- They only work with records
- They necessarily replace all other constructors
Show answer
Correct: The parameters are available in the class body but do not automatically become properties
Unlike with records, primary constructors in classes do not create properties; the parameters are captured as (private) fields only when needed.
How do you cooperatively cancel a running asynchronous operation?
- With
Thread.Abort() - With a
CancellationToken - With
Task.Kill() - With
GC.Collect()
Show answer
Correct: With a CancellationToken
The operation checks the token or passes it on (e.g. Task.Delay(ms, token)); on cancellation an OperationCanceledException is raised.
What does this code print?
int[] a = { 1, 2, 3, 4 };
Console.WriteLine(a is [1, .., 4]);- True
- False
- Compiler error
- 4
Show answer
Correct: True
The list pattern [1, .., 4] requires: first element 1, last element 4, any number of elements in between.
What distinguishes record struct from record (class)?
- No difference
record structis a value type and is copied on assignmentrecord structcannot be comparedrecord structis always mutable and has no ToString
Show answer
Correct: record struct is a value type and is copied on assignment
record struct has value-based equality like records but is a value type (copy on assignment, no heap allocation as a field).