C#/.NET interview questions

25 questions from the C#/.NET course, each with the correct answer and an explanation. Try to answer before you open the answer.

C# and the .NET Platform

1. What does the JIT compiler in the CLR do?

  1. Turns IL into native machine code while the program runs
  2. Turns C# into IL at build time
  3. Collects unused objects
  4. Downloads NuGet packages
Show answer

Answer: Turns IL into native machine code while the program runs

Roslyn produces IL at build time; the JIT converts IL to native code at run time.

Lesson: What .NET Is

2. What do top-level statements in Program.cs do?

  1. Disable classes in the project
  2. Make the program run without the CLR
  3. Turn on nullable reference types
  4. Let you write statements directly; the compiler generates the Main method
Show answer

Answer: Let you write statements directly; the compiler generates the Main method

The compiler wraps top-level statements in a generated entry point.

Lesson: Projects, Program.cs and the dotnet CLI

3. Which type should you use for currency amounts in C#?

  1. float
  2. double
  3. decimal
  4. int with implicit rounding
Show answer

Answer: decimal

decimal is a base-10 type designed for financial values, avoiding binary floating-point rounding errors.

Lesson: Types, Variables and Value vs Reference

Control Flow, Methods and Pattern Matching

4. What happens if you remove an item from a `List<T>` inside a foreach over that list?

  1. It works and skips the removed item
  2. The loop restarts from the beginning
  3. An InvalidOperationException is thrown
  4. It compiles to a for loop automatically
Show answer

Answer: An InvalidOperationException is thrown

Modifying a list during foreach invalidates its enumerator, which throws.

Lesson: Branches and Loops

5. Which modifier requires the called method to assign the parameter before returning?

  1. ref
  2. out
  3. in
  4. params
Show answer

Answer: out

out parameters must be definitely assigned by the method, as in TryParse.

Lesson: Methods and Parameters

6. What does `_` mean in a switch expression?

  1. The discard pattern that matches any value not matched earlier
  2. A syntax error
  3. A null check
  4. The default value of the type
Show answer

Answer: The discard pattern that matches any value not matched earlier

The discard pattern catches everything that earlier arms did not match.

Lesson: Switch Expressions and Pattern Matching

Classes, Interfaces and Records

7. What does the `required` modifier on a property do?

  1. Forces callers to set it when creating the object, or the code does not compile
  2. Makes the property read-only forever
  3. Validates the value at run time
  4. Makes the property static
Show answer

Answer: Forces callers to set it when creating the object, or the code does not compile

Required members must be initialised in the object initializer (or by a constructor marked SetsRequiredMembers).

Lesson: Classes, Constructors and Properties

8. A class needs behaviour from two unrelated contracts. What does C# allow?

  1. Inheriting from two base classes
  2. Neither; C# allows only one of each
  3. Using the new keyword on both
  4. Implementing two interfaces
Show answer

Answer: Implementing two interfaces

C# supports single class inheritance but multiple interface implementation.

Lesson: Inheritance, Interfaces and Polymorphism

9. Two record instances are created with identical property values. What does == return?

  1. False, because they are different objects
  2. It does not compile
  3. True, because records use value-based equality
  4. It depends on the garbage collector
Show answer

Answer: True, because records use value-based equality

Records generate equality members that compare property values.

Lesson: Records, Structs and Equality

Generics, Nullability and Delegates

10. How do .NET generics differ from Java generics?

  1. .NET generics are erased at run time
  2. .NET has no generic constraints
  3. .NET generics are reified, so the runtime knows the type arguments and value types avoid boxing
  4. .NET generics only work with classes
Show answer

Answer: .NET generics are reified, so the runtime knows the type arguments and value types avoid boxing

.NET keeps generic type information at run time and specialises code for value types.

Lesson: Generics and Constraints

11. With nullable reference types enabled, what does `string?` mean?

  1. A string that is always null
  2. A string variable that may be null, so the compiler checks uses of it
  3. A nullable value type
  4. A string stored on the stack
Show answer

Answer: A string variable that may be null, so the compiler checks uses of it

The ? annotation marks a reference as possibly null, enabling compile-time null-safety warnings.

Lesson: Nullable Types and Null Safety

12. Which delegate type fits a method that takes a string and returns nothing?

  1. Action<string>
  2. Func<string>
  3. Predicate<string>
  4. Func<string, bool>
Show answer

Answer: Action<string>

`Action<T>` represents methods with parameters and no return value.

Lesson: Delegates, Lambdas and Events

Collections, LINQ and Iterators

13. You need to check thousands of times whether an ID has been seen. Which collection fits best?

  1. HashSet<T>
  2. List<T>
  3. Queue<T>
  4. LinkedList<T>
Show answer

Answer: HashSet<T>

`HashSet<T>` offers near constant-time membership checks.

Lesson: Choosing a Collection

14. When does a LINQ query like `orders.Where(o => o.Total > 500)` actually run?

  1. When the line is executed
  2. At compile time
  3. Only when the garbage collector runs
  4. When it is enumerated, for example by foreach or ToList()
Show answer

Answer: When it is enumerated, for example by foreach or ToList()

Most LINQ operators are deferred and execute on enumeration.

Lesson: LINQ

15. Why can enumerating the same `IEnumerable<T>` twice be a problem?

  1. It never compiles
  2. The second enumeration is always empty
  3. The underlying work, such as a database query or file read, may run twice
  4. It converts the sequence to an array
Show answer

Answer: The underlying work, such as a database query or file read, may run twice

Lazy sequences re-execute on each enumeration unless materialised.

Lesson: IEnumerable and yield return

Asynchronous and Concurrent Programming

16. What happens to the thread when an async method awaits an HTTP call that is still in progress?

  1. It sleeps until the call finishes
  2. It throws a TimeoutException
  3. It returns to the thread pool to do other work
  4. It spins in a loop checking the result
Show answer

Answer: It returns to the thread pool to do other work

await releases the thread; the remainder of the method resumes when the operation completes.

Lesson: async and await

17. How should a long-running async operation be stopped when the user cancels a request?

  1. Call Thread.Abort
  2. Pass a CancellationToken through the call chain and let operations observe it
  3. Use .Result to block it
  4. Throw an exception from another thread
Show answer

Answer: Pass a CancellationToken through the call chain and let operations observe it

Cancellation in .NET is cooperative via CancellationToken.

Lesson: Concurrency with Tasks and Cancellation

18. Why can you not use `lock` around an `await`?

  1. The method may resume on a different thread, and the compiler forbids await inside lock; use SemaphoreSlim instead
  2. lock is deprecated
  3. await is not allowed in classes with locks
  4. lock only works with value types
Show answer

Answer: The method may resume on a different thread, and the compiler forbids await inside lock; use SemaphoreSlim instead

Monitor-based locks are thread-affine, so the compiler disallows await inside lock blocks.

Lesson: Threads, Locks and Thread Safety

Memory, Exceptions and Performance

19. What does a `using` declaration guarantee?

  1. Dispose() is called when the scope ends, even if an exception is thrown
  2. The object is garbage-collected immediately
  3. The object is allocated on the stack
  4. The object becomes thread-safe
Show answer

Answer: Dispose() is called when the scope ends, even if an exception is thrown

using ensures Dispose runs at the end of scope, releasing resources deterministically.

Lesson: Garbage Collection and IDisposable

20. Why prefer `throw;` over `throw ex;` when rethrowing?

  1. throw; is faster to type
  2. throw ex; does not compile
  3. throw; converts the exception to a warning
  4. throw; preserves the original stack trace
Show answer

Answer: throw; preserves the original stack trace

throw ex; resets the stack trace to the current location, hiding the real origin.

Lesson: Exceptions

21. What is `Span<T>` mainly used for?

  1. Running code on another thread
  2. Serialising objects to JSON
  3. Working with slices of contiguous memory without copying or allocating
  4. Storing data in a database
Show answer

Answer: Working with slices of contiguous memory without copying or allocating

`Span<T>` is a lightweight view over memory that enables allocation-free slicing.

Lesson: Allocation-Aware Code: Span, Strings and Boxing

Tooling, Modern C# and Revision

22. Where can you set shared properties such as Nullable for every project in a repository?

  1. Program.cs
  2. appsettings.json
  3. Directory.Build.props
  4. global usings
Show answer

Answer: Directory.Build.props

Directory.Build.props is imported by all projects below it, so shared MSBuild settings live there.

Lesson: NuGet, Testing and Analyzers

23. What does the C# 14 `field` keyword refer to inside a property accessor?

  1. A database column
  2. The compiler-generated backing field of that property
  3. Any field in the class
  4. A static field
Show answer

Answer: The compiler-generated backing field of that property

field gives accessors access to the auto-generated backing field, so you can add logic without declaring one.

Lesson: Modern C# Features

24. Which comparison is recommended for checking a role name such as "admin" regardless of case?

  1. string.Equals(role, "admin", StringComparison.OrdinalIgnoreCase)
  2. role.ToLower() == "admin"
  3. role.ToUpper(CultureInfo.CurrentCulture) == "ADMIN"
  4. role.GetHashCode() == "admin".GetHashCode()
Show answer

Answer: string.Equals(role, "admin", StringComparison.OrdinalIgnoreCase)

Ordinal ignore-case comparison is culture-independent and does not allocate new strings.

Lesson: Idiomatic C# and Common Pitfalls

25. Which statement about `async void` methods is true?

  1. They are the recommended return type for async library methods
  2. They run synchronously
  3. They return a Task automatically
  4. Their exceptions cannot be caught by the caller, so use them only for event handlers
Show answer

Answer: Their exceptions cannot be caught by the caller, so use them only for event handlers

Callers cannot await async void methods or catch their exceptions; prefer Task-returning methods.

Lesson: C# Revision and Interview Questions

← Back to the course