C#C#

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#?

  1. Console.Print("Hi");
  2. Console.WriteLine("Hi");
  3. System.out.println("Hi");
  4. 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?

  1. 3.5
  2. 3
  3. 4
  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#?

  1. 2
  2. 1
  3. -1
  4. -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?

  1. float
  2. double
  3. int
  4. 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);
  1. 5
  2. 3
  3. 53
  4. 8
Show answer

Correct: 8

x += 3 is equivalent to x = x + 3, so 8.

What does var zahl = 42; mean?

  1. A dynamic type like in JavaScript
  2. The compiler infers int; the type stays fixed
  3. zahl has the type object
  4. 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}");
  1. Ada is 36
  2. Ada is 37
  3. Ada is {alter + 1}
  4. 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?

  1. a[-1]
  2. a[^1]
  3. a[last]
  4. 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);
  1. 012
  2. 123
  3. 0123
  4. 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?

  1. final
  2. let
  3. const
  4. 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?

  1. Throws a FormatException
  2. Returns false; n is 0
  3. Returns null
  4. Returns true; n is 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?

  1. It always needs class Program and static void Main
  2. A single line Console.WriteLine("Hi"); is enough (top-level statements)
  3. It needs a header file
  4. 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");
  1. no
  2. yes
  3. True
  4. 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?

  1. for
  2. foreach
  3. while
  4. 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)));
  1. 10,6,16
  2. 5,3,8
  3. 10,16
  4. 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());
  1. 2
  2. 3
  3. 4
  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);
  1. True
  2. False
  3. Compiler error
  4. 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?

  1. Checks whether two values are equal
  2. Returns the left value if it is not null, otherwise the right one
  3. Throws an exception on null
  4. 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);
  1. 0
  2. -1
  3. Empty line
  4. 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");
  1. ACBD
  2. ABCD
  3. ACD
  4. 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?

  1. Records are always value types
  2. Records have value-based equality, ToString and with copies built in
  3. Records cannot be inherited
  4. 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);
  1. 2
  2. 3
  3. 1
  4. 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?

  1. Imports a namespace
  2. Dispose() is called automatically at the end of the enclosing block
  3. The file stays open until the program ends
  4. 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?

  1. No difference
  2. throw; keeps the original stack trace, throw e; overwrites it
  3. throw; finally swallows the exception
  4. throw 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);
  1. small
  2. medium
  3. large
  4. 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);
  1. 13
  2. 12
  3. 11
  4. 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?

  1. null is returned
  2. 0 is returned
  3. A KeyNotFoundException is thrown
  4. 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);
  1. True
  2. False
  3. 42
  4. 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?

  1. The thread is blocked until the task is finished
  2. The method pauses; the thread is freed and the method continues later
  3. It automatically starts a new thread per call
  4. 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?

  1. 3 seconds
  2. 1 second
  3. 0 seconds
  4. 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?

  1. The methods no longer exist
  2. They can block threads and cause deadlocks
  3. They always return null
  4. 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?

  1. For all methods without a return value
  2. Only for event handlers
  3. For constructors
  4. 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;
}
  1. AB12X
  2. XA1B2
  3. A1B2X
  4. 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; }
  1. 5
  2. 1
  3. 0
  4. 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?

  1. T must be a value type with a default value
  2. T must be a reference type with a parameterless constructor
  3. T must inherit from a class named new
  4. 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?

  1. For sorting lists
  2. As a view over contiguous memory without copying and without heap allocation
  3. As a replacement for threads
  4. 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?

  1. The parameters automatically become public properties
  2. The parameters are available in the class body but do not automatically become properties
  3. They only work with records
  4. 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?

  1. With Thread.Abort()
  2. With a CancellationToken
  3. With Task.Kill()
  4. 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]);
  1. True
  2. False
  3. Compiler error
  4. 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)?

  1. No difference
  2. record struct is a value type and is copied on assignment
  3. record struct cannot be compared
  4. record struct is 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).