C# Interview Questions: Modern C# Features Quiz

Reviewed by Mark Dickie · Last updated

4 questions on this page you can answer and see marked on the spot. Go to the first one

C# is a statically typed, object-oriented language that runs on .NET, and interviewers now test how you use its recent features as much as its syntax. Expect questions on records, pattern matching, nullable reference types, and async streams, along with what the compiler generates for each. Answers that name the generated code and the compiler warnings hold up under follow-up questions better than memorized definitions.

Which modern C# features do interviewers test most?

Feature (introduced)What to knowFollow-up interviewers ask
Records (C# 9)Value equality, positional syntax, with expressionsIs the copy made by with deep or shallow?
Nullable reference types (C# 8)Flow analysis, string? annotations, warnings CS8600 to CS8629Does the null-forgiving ! change anything at runtime?
Pattern matching (C# 8 onward)Switch expressions, property and list patternsWhat happens when a switch expression has no matching arm?
Primary constructors (C# 12)Parameters captured in the class bodyWhich parameters become fields, and when does the compiler create one?
Collection expressions (C# 12)[1, 2, 3] target-typed to arrays, List<T>, and spansWhy can the same [] literal compile to different code for an array and a List<T>?
Async streams (C# 8)IAsyncEnumerable<T>, await foreach, [EnumeratorCancellation]How does a CancellationToken reach an async iterator method?

How do you practice these features before the interview?

  1. Convert a class with a constructor and four fields into a record, then write a test that shows with leaves the original object unchanged.
  2. Turn on nullable reference types with warnings treated as errors, then clear every warning without using the ! operator.
  3. Rewrite an if/else chain that checks type and property values as a switch expression, and trigger the compiler warning for a missing arm.
  4. Write an async iterator that yields rows from a fake data source, then consume it with await foreach and cancel it midway.

Key facts

  • Tarmac has 15 C# interview questions on this topic, 10 of them on this page, at difficulty 1–5 of 5.
  • Tarmac tracked 871 job postings asking for C# in November 2026.
  • Roles asking for C# advertise a median base salary of £70,000, across 342 job postings as of November 2026.
  • Tarmac last reviewed these C# interview questions on 3 December 2026.

At a glance

Questions10 shown · 15 in the bank
Difficulty1–5 of 5
FormatsMultiple choice, Ordering, Code output, Multiple answer, True / false, Find the bug, Short answer, Fill in the blank, Flashcard

What you'll review

  1. init only properties
  2. nullable reference types
  3. pattern matching csharp

Practice questions

Try one before you open the answer. Pick an option and press Check; it's marked on the spot.

In C# 9 and later, given public class Person { public string Name { get; init; } }, which statement is valid?#

Options

Show answer

A C# init-only property can be set in an object initializer, such as new Person { Name = "Ann" }. It can also be set in a constructor or a with expression. Once the object is constructed, assigning the property again, as in p.Name = "Bob", causes a compile-time error. This makes the property immutable after initialization.

Why:

An init accessor allows assignment only during object initialization: in an object initializer, a constructor, or a with expression. new Person { Name = "Ann" } uses an object initializer, so it compiles. Assigning p.Name after construction is a compile-time error (CS8852), whether or not an initializer ran first. Person.Name is an instance property, so it can't be accessed through the type name.

Arrange these null-handling features in the order they were first added to C#, earliest first.#

Put these in order

Show answer

C# null-handling features in release order: nullable value types int? (C# 2.0), the null-conditional operator ?. (C# 6.0), nullable reference types string? (C# 8.0), the is not null pattern (C# 9.0), and required members (C# 11). Nullable reference types came after ?.. Later features such as required work with them to make non-nullable values safer.

Why:

Nullable value types (int?) came with C# 2.0. The null-conditional operator ?. was added in C# 6.0. Nullable reference types, where you annotate string? and the compiler warns about possible null dereferences, arrived in C# 8.0. The is not null pattern came with the logical patterns in C# 9.0. required members, which make callers initialize non-nullable properties, were added in C# 11.

What does this C# program print?#

object value = 42;
if (value is int n)
{
    Console.WriteLine(n + 1);
}
else
{
    Console.WriteLine("not an int");
}
Show answer
43
Why:

The variable value holds a boxed int with the value 42. The type pattern value is int n checks whether the runtime type is int. It is, so the check returns true and the unboxed value goes into the new variable n. The if branch then runs and prints n + 1, which is 43. The else branch never runs.

Given this C# 9+ class:#

Options

Pick every one that applies.

Show answer

In C# 9 and later, an init-only property can be set in an object initializer, inside the type's own constructor, or in a with expression on a record. That includes a constructor call followed by an initializer. Assigning the property in a separate statement after the object is built is compile error CS8852. This makes the property immutable once initialization ends.

Why:

An init accessor can be called only while the object is being initialized. That covers object initializers, assignments inside the type's own constructors, and with expressions on records. The object initializer new Person { Name = "Ada" } and the constructor assignment Name = name both compile. Combining a constructor call with an initializer, as in new Person("Ada") { Name = "Grace" }, also compiles. The constructor runs first, then the initializer sets the property again, so Name ends up as "Grace". Writing p.Name = "Ada" as a separate statement after construction is a compile error (CS8852), because initialization has already finished.

With #nullable enable in C# 12 (.NET 8), what does this program print? (Assume it compiles; warnings are ignored.)#

#nullable enable
using System;

class Program
{
    static void Main()
    {
        string? name = null;
        int? len = name?.Length;
        string display = name ?? "guest";
        Console.WriteLine($"{len ?? -1} {display} {display.Length}");
    }
}
Show answer
-1 guest 5
Why:

name is null, so name?.Length short-circuits and gives a null int?. That makes len ?? -1 evaluate to -1. Next, name ?? "guest" falls back to "guest", so display is "guest" and its length is 5. Nullable reference type annotations like string? only affect the compiler's static analysis. They do not change runtime behavior, so no exception is thrown and the program prints -1 guest 5.

In C# 9 (language version 9.0), given public class Person { public string Name { get; init; } }, the following code compiles: var p = new Person { Name = "Ann" }; var q = p with { Name = "Bob" };#

Options

Show answer

False. In C# 9, this code does not compile. The initializer new Person { Name = "Ann" } is valid because init-only properties can be set in object initializers, but the with expression requires a record type, which gets a compiler-generated copy method. A plain class like Person lacks that method, so the with line fails.

Why:

Init-only setters can be assigned in object initializers, so new Person { Name = "Ann" } is valid. The problem is the with expression. In C# 9, with is defined for record types, because the compiler generates a copy method for records that the with expression calls. Person is an ordinary class without that generated method, so p with { Name = "Bob" } is a compile error even though Name is init-only. Declaring Person as a record would make the code compile.

This C# 12 project has <Nullable>enable</Nullable> turned on. It compiles with no nullable warnings, yet it can throw a NullReferenceException at runtime. Which line contains the bug?#

#nullable enable
public class UserService
{
    private readonly Dictionary<int, string> _names = new();

    public string? FindName(int id)
        => _names.TryGetValue(id, out var name) ? name : null;

    public int NameLength(int id)
    {
        string? name = FindName(id);
        return name!.Length;
    }
}
Show answer

The bug is on line 12.

Why:

FindName returns string? and does return null when the id is missing. On line 12, the null-forgiving operator ! only switches off the compiler's warning. It adds no runtime check, so name!.Length throws NullReferenceException whenever the lookup fails. Nullable reference types are a compile-time analysis only, and ! tells the compiler to trust the developer. The fix is to handle the null case, for example return name?.Length ?? 0;, or to throw a meaningful exception. The other lines are correct: line 7 returns null through a return type correctly declared as string?, and line 11 stores the result in a variable correctly declared as nullable.

In C# 9+, a class declares public string Name { get; init; }. Explain (1) at which points in code the init accessor may legally be invoked, (2) how the compiler enforces this at the IL/metadata level so that older compilers (e.g. C# 8) cannot call the setter, and (3) why init does not guarantee deep immutability — give a concrete way the object's observable state can still change after construction.#

Show answer

(1) An init accessor can be called only during object initialization: inside an object initializer (new P { Name = "x" }), a with expression on records, inside the type's own constructors (or derived constructors via this/base), and inside other init accessors of the same object. Assigning it afterwards (p.Name = "y") is a compile error. (2) The compiler emits a normal setter method set_Name, but its return type carries a required custom modifier modreq(System.Runtime.CompilerServices.IsExternalInit). Compilers that don't understand that modreq refuse to call the method, so older C# compilers cannot invoke it; this is compile-time enforcement only — reflection can still call the setter at runtime. (3) init only prevents reassigning that property reference after initialization; it is shallow. If Name were a List<string> with { get; init; }, callers can still Add to the list, mutating observable state. Also reflection or other mutable members/fields can alter state.

Why:

Init-only setters restrict assignment to the initialization phase (object initializers, with expressions, constructors, other init accessors). The compiler encodes this by marking the setter's return with a modreq of IsExternalInit, which unaware compilers reject; the runtime does not enforce it, so reflection bypasses it. Since only the property slot is protected, referenced mutable objects (e.g. a list) can still be mutated, so immutability is shallow.

In C# 12 with #nullable enable, fill in the attribute names from System.Diagnostics.CodeAnalysis so that this code produces no nullable warnings:#

Show answer

In C# 12 with #nullable enable, fill in the attribute names from System.Diagnostics.CodeAnalysis so that this code produces no nullable warnings:

class Cache
{
    private string _name;

    public Cache() => Init(); // no CS8618 warning for _name

    [**MemberNotNull**(nameof(_name))]
    private void Init() => _name = "default";

    public bool TryGet(string key, [**NotNullWhen**(true)] out string? value)
    {
        value = key == _name ? "hit" : null;
        return value is not null;
    }
}

// caller:
if (cache.TryGet("k", out var v))
    Console.WriteLine(v.Length); // no CS8602 warning

Give only the attribute names, without the Attribute suffix.

Why:

The first blank is MemberNotNull. The constructor does not assign _name itself, so the compiler would normally report CS8618: a non-nullable field is left uninitialized when the constructor exits. Putting [MemberNotNull(nameof(_name))] on Init tells the flow analysis that _name is non-null after the call returns, so the warning goes away. The attribute also makes the compiler check that Init really does assign the field. The second blank is NotNullWhen. Writing [NotNullWhen(true)] on the out string? value parameter means: when the method returns true, value is not null. So inside the if (cache.TryGet(...)) branch, v counts as not-null, and calling v.Length causes no CS8602 warning. Other attributes do not fit here. NotNull would claim the value is never null, even when the method returns false. MaybeNullWhen(false) is meant for a non-nullable string parameter, not for string?.

In C# 9+, how is an init accessor encoded in compiled metadata? What does that mean for (a) compilers that don't understand init, (b) targeting older frameworks such as .NET Framework or netstandard2.0, and (c) reflection?#

Show answer

An init accessor compiles to an ordinary set_X method. Its return type carries a required custom modifier, modreq(System.Runtime.CompilerServices.IsExternalInit). (a) Older compilers such as C# 8 don't recognise the modreq, so they refuse to call the setter. That keeps them from mutating the property after construction. Because the modreq is part of the method signature, changing set to init (or back) is a binary-breaking change. (b) IsExternalInit only ships with .NET 5 and later. For older targets you can declare your own internal static class IsExternalInit {} in that namespace, or use a polyfill package, and the compiler will accept it. (c) Neither the runtime nor reflection enforces init-only. PropertyInfo.SetValue can still set the value after construction. You can detect init-only properties by checking GetRequiredCustomModifiers() on the setter's ReturnParameter for IsExternalInit.

Why:

Init-only is a compile-time rule. The compiler encodes it as a modreq on the setter's return type. That design explains all three answers: older compilers reject the setter, older frameworks need a polyfill type, and reflection can still set the value. It also explains why switching between set and init breaks existing binaries.

Related interview questions

Job market

See csharp salaries and hiring demand from live job postings.

The other 5 questions

This page shows 10 and marks what you pick. That's as far as a page can go. A free account opens the other 5 and keeps every answer. What you miss comes back until it's right: after a day, then at longer gaps.

Start with this topic

Free · the whole bank · 100 answers per 30 days, each marked with written feedback

Interview booked? Practise the job ad instead

What moved, monthly

One email a month when the bulletin comes out: what moved in the markets we track, and the new question topics we published. Confirm your address to join. Unsubscribe any time.