Skip to content
Tutorials Center
My learning

Topics

Lesson 182 of 182 ยท Practice and Review

C# Interview Questions and Answers

Fifty C# interview questions with concise answers and runnable examples: CLR, value vs reference types, GC, generics, LINQ, async, DI and ASP.NET Core.

Interviews for C# roles keep returning to the same topics: how the runtime works, the difference between value and reference types, how collections and LINQ behave, how async really works, and how dependency injection and ASP.NET Core fit together. This page collects fifty questions in those areas with answers short enough to say out loud, plus small programs that prove the tricky ones.

How to use it: cover the answer, say yours aloud in two or three sentences, then compare. A good interview answer states the rule, gives one reason, and mentions one pitfall or trade-off. If you can also name where the idea shows up in real code, you are ahead of most candidates. Every question links to the lesson that teaches the topic in depth.

Do not memorize wording. Interviewers can tell. Memorize the shape of an answer: definition, why it matters, one example, one gotcha.

Part 1: language and runtime

1. What is the difference between the CLR, the BCL and the SDK? The CLR (Common Language Runtime) executes your compiled code: it loads assemblies, JIT-compiles IL to machine code, manages memory and enforces type safety. The BCL (Base Class Library) is the set of types you call, such as List<T> and File. The SDK is the toolchain (compiler, dotnet CLI, templates) that builds your project. See How C# and .NET work.

2. What happens between writing C# and running it? Roslyn compiles source to IL (intermediate language) and metadata inside an assembly (.dll). At run time the JIT compiles each method to native code the first time it is called, and tiered compilation later recompiles hot methods with more optimization. Native AOT instead compiles ahead of time, trading flexibility such as reflection for fast startup. See IL, JIT and tiered compilation.

3. What is the difference between .NET, .NET Framework and .NET Standard? .NET Framework is the old Windows-only runtime (final version 4.8). Modern .NET (5 and later, currently .NET 10 LTS) is cross-platform and open source, and it is where new features land. .NET Standard was an API contract for sharing libraries across runtimes; new libraries should simply target modern .NET (and netstandard2.0 only when old consumers matter).

4. What are top-level statements? A C# 9 feature that lets the entry point be loose statements at the top of one file; the compiler generates the Program class and Main method. Only one file in a project can use them, and type declarations must come after the statements. See Program structure.

5. What is the difference between const and readonly? A const is a compile-time constant baked into the callers' IL; it must be a primitive, string or null. A readonly field is assigned at run time, in a declaration or constructor, and can hold any type. Changing a const in a library means recompiling every consumer, which is why public values that might change should be static readonly. See Constants.

6. What is the difference between == and Equals for strings and objects? For reference types == compares references unless the type overloads it; string overloads == to compare content, so == and Equals agree for strings. Equals is virtual and can be overridden; == is chosen at compile time from the static types. See The object class.

7. What are ref, out and in parameters? ref passes a variable by reference so the callee can read and change it. out also passes by reference but the callee must assign it before returning (the caller need not initialize it). in passes by read-only reference, which avoids copying large structs. See Parameters.

8. What does var do? It asks the compiler to infer the static type from the initializer. The variable is still strongly typed; var x = 5; is an int. It is not dynamic. Use it when the type is obvious from the right-hand side. See Variables.

Part 2: types and memory

9. Value types versus reference types? A value-type variable holds its data directly (structs, enums, primitives); assigning copies the data. A reference-type variable holds a reference to an object on the heap (classes, strings, arrays, delegates); assigning copies the reference, so two variables can see the same object.

C# Value copy versus reference copy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

See Value types and reference types.

10. Is a struct always on the stack? No. A struct local variable may live on the stack, but a struct field of a class lives inside the heap object, a struct in an array lives in the array, and a captured variable lives in a closure object. "Value type" describes copy semantics, not a memory location. See Structs.

11. When should you choose a struct over a class? For small (roughly 16 bytes or less), immutable, short-lived values with value semantics, such as coordinates or a money amount. Avoid large or mutable structs: they are copied on every assignment and call, and mutating a copy by mistake is a classic bug. readonly struct and record struct help.

12. What are boxing and unboxing? Boxing wraps a value type in an object on the heap; unboxing copies it back out with a cast. Boxing allocates and shows up in hot paths through non-generic collections, object parameters and interface calls on structs. Generics remove most of it. See Boxing and unboxing.

C# Boxing in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

13. Why are strings immutable, and what is interning? Immutability makes strings safe to share across threads, cacheable and usable as dictionary keys. Operations like += create new strings, so many appends in a loop are O(n squared); use StringBuilder. Literals are interned (one shared instance per distinct literal), which makes ReferenceEquals true for equal literals but not for computed strings. See Strings and StringBuilder.

14. How does the garbage collector work? The GC is generational and tracing: new objects start in generation 0; survivors move to 1, then 2. Most objects die young, so cheap gen-0 collections reclaim most memory. Objects of 85,000 bytes or more go to the large object heap, which is collected with gen 2. A collection finds objects reachable from roots (stacks, statics, handles) and frees the rest. See Garbage collection.

15. What is the difference between Dispose and a finalizer? Dispose (from IDisposable) is deterministic: you or a using block call it to release unmanaged resources such as file handles right now. A finalizer runs at an unspecified time on the GC's schedule, as a safety net, and makes the object survive an extra collection. Prefer SafeHandle over writing finalizers. See IDisposable and using.

16. What causes a memory leak in a managed language? Objects stay reachable when they should not: static collections that only grow, event handlers never unsubscribed (the publisher keeps the subscriber alive), long-lived caches without limits, captured variables in long-lived closures, and undisposed unmanaged resources.

17. What is Span<T> and why is it useful? A ref struct that views a contiguous region of memory (array, stack memory or native memory) without copying. Slicing a span is O(1) and allocation-free, which makes parsing and formatting fast. Because it can live only on the stack, it cannot be a field of a class or be used across await. See Span and Memory.

18. What is the difference between Nullable<T> and nullable reference types? int? is a real type, Nullable<int>, a struct with a value and a HasValue flag. string? is only an annotation that the compiler uses for flow analysis; at run time there is no difference between string and string?. NRTs produce warnings, not guarantees. See Nullable value types and Nullable reference types.

Part 3: OOP and design

19. What are the four pillars of OOP, in C# terms? Encapsulation (hide state behind members with access modifiers), inheritance (a class derives from one base), polymorphism (a base reference calls the derived override) and abstraction (abstract classes and interfaces define contracts). Modern C# also leans on composition and immutability.

20. Abstract class versus interface? An abstract class can hold state, constructors and implemented members, and a class can inherit only one. An interface defines a contract (and, since C# 8, optional default implementations), and a class can implement many. Use an interface for a capability, an abstract class when subclasses share code and state. See Abstract classes and interfaces.

21. What is the difference between virtual/override and new? override replaces the base implementation and is chosen by the runtime type. new hides the base member: the method called depends on the compile-time type of the variable, which is usually a bug.

C# override versus new

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

See Polymorphism.

22. What is a sealed class? A class that cannot be inherited (and a sealed override stops further overriding). It documents design intent and lets the JIT devirtualize calls. Make classes sealed unless you design them for inheritance.

23. What is a record, and how does it differ from a class? A record is a type (class by default, or record struct) with compiler-generated value-based equality, ToString, with expressions and deconstruction. Two records are equal when their properties are equal. Use records for data and DTOs; use classes for entities with identity and behavior. See Records.

24. What is the difference between init and set? An init accessor can be called only during object initialization (constructor, object initializer, with), so the property is effectively read-only afterwards. required forces callers to set it. Together they make immutable objects easy to build.

25. How do you override Equals and GetHashCode correctly? Equal objects must produce the same hash code. Override both together, compare the same fields in both, base the hash on immutable fields (mutating a key inside a dictionary breaks lookups), and implement IEquatable<T> to avoid boxing. Records do all of this for you. See The object class.

26. What are SOLID principles in one line each? Single responsibility (one reason to change), open/closed (extend without editing), Liskov substitution (subtypes must honor the base contract), interface segregation (small focused interfaces) and dependency inversion (depend on abstractions). See Designing with objects.

Part 4: generics, delegates and LINQ

27. What are generics, and what are constraints? Generics let a type or method work over a type parameter while staying type-safe and, for value types, boxing-free (the JIT creates specialized code per value type). Constraints such as where T : class, new(), IComparable<T> or struct tell the compiler what operations T supports. See Generics and Constraints.

28. What are covariance and contravariance? Covariance (out) lets IEnumerable<string> be used as IEnumerable<object> because it only produces values. Contravariance (in) lets Action<object> be used as Action<string> because it only consumes values. They apply to interfaces and delegates, not classes. See Variance.

29. What is a delegate? How does it relate to Func, Action and events? A delegate is a type-safe object that refers to one or more methods. Func<...> and Action<...> are ready-made generic delegates (with and without a return value). An event is a delegate field with restricted access: outside code can only += and -=, not invoke it or replace the list. See Delegates and Events.

30. What is a closure, and what is the classic trap? A lambda that uses a local variable captures the variable, not its value. Since C# 5, each foreach iteration has its own variable, but a for loop shares one counter, so lambdas created in the loop all see the final value.

C# Closure capture in for and foreach

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

31. What is deferred execution in LINQ? Query operators such as Where and Select build a pipeline; nothing runs until you enumerate it with foreach, ToList, Count and so on. Each new enumeration runs the query again, so it sees changes to the source and repeats side effects.

C# Deferred execution

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

See Deferred execution.

32. IEnumerable<T> versus IQueryable<T>? IEnumerable<T> runs in memory with delegates. IQueryable<T> builds an expression tree that a provider (such as Entity Framework Core) translates into SQL, so filtering happens in the database. Calling ToList() or using a non-translatable method too early pulls everything into memory. See Expression trees.

33. First, FirstOrDefault, Single, SingleOrDefault? First throws if there is no match; FirstOrDefault returns default. Single demands exactly one match and throws for zero or more than one; SingleOrDefault allows zero. Use Single to assert uniqueness, First when any match will do.

34. What does yield return do? It turns a method into a lazy state machine that produces items one at a time. Local state is kept between MoveNext calls, and code before the first yield runs only on the first iteration (so argument validation should be in a wrapper method). See Iterators and yield.

35. Which collection would you pick for...? Index access: List<T> or array. Key lookup: Dictionary<K,V>. Uniqueness: HashSet<T>. Sorted keys: SortedDictionary or SortedSet. FIFO/LIFO: Queue/Stack. Priority: PriorityQueue. Read-heavy, built once: FrozenDictionary. Many threads: ConcurrentDictionary or Channel<T>. See Choosing collections.

36. How does a Dictionary work, and what makes a good key? It hashes the key (GetHashCode) into a bucket and compares keys with Equals inside the bucket, giving O(1) average lookups. Keys must be immutable with a consistent hash; a poor hash degrades lookups towards O(n). Never rely on enumeration order. See Dictionaries.

Part 5: errors and async

37. How do exceptions work, and when should you not use them? throw unwinds the stack to the nearest matching catch; finally always runs. Exceptions are for exceptional conditions, not control flow: they are slow compared to a TryParse check. Catch only what you can handle, rethrow with throw; (not throw ex;, which resets the stack trace). See Exceptions.

38. What are exception filters? catch (X ex) when (condition) evaluates the condition before unwinding, so the stack is intact for the debugger and non-matching exceptions fly past without being caught and rethrown. See Exception filters.

39. What does async/await actually do? The compiler rewrites an async method into a state machine. At each await on an incomplete task, the method returns to its caller and registers the rest as a continuation; when the awaited operation completes, the method resumes. No thread is blocked while waiting for I/O. async does not create threads by itself. See async and await.

40. Task versus Thread; Task.Run versus plain async? A Thread is an OS thread you manage. A Task represents an operation (often scheduled on the thread pool, sometimes with no thread at all, as with I/O). Task.Run queues CPU-bound work to the pool; for I/O call the async API directly. See Tasks.

41. Why is async void bad? Nobody can await it, exceptions cannot be caught by the caller (they crash the process or go to the synchronization context), and it is hard to test. Use async Task; keep async void only for event handlers. See Async pitfalls.

42. What is a deadlock with .Result, and how do you avoid it? In environments with a single-threaded synchronization context (older ASP.NET, UI apps), blocking on task.Result ties up the thread the continuation needs to resume, so both wait forever. Avoid it by awaiting all the way up ("async all the way"). ASP.NET Core has no such context, but blocking still wastes threads.

43. ConfigureAwait(false): when and why? It tells the awaiter not to resume on the captured context. Libraries use it to avoid needless context hops and deadlocks; application code in ASP.NET Core usually does not need it because there is no context.

44. How does Task.WhenAll handle failures? It waits for all tasks. If any failed, the returned task faults with all exceptions, but await rethrows only the first one; the others are available on task.Exception.InnerExceptions.

C# WhenAll with failures

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

See Task combinators.

45. How do you cancel an async operation? Cooperatively: create a CancellationTokenSource, pass its Token down through every async call, and have long loops call token.ThrowIfCancellationRequested(). The operation throws OperationCanceledException. See Cancellation.

46. lock versus Interlocked versus SemaphoreSlim? Interlocked performs one atomic operation on a variable (increment, exchange). lock (with System.Threading.Lock in .NET 9+) protects a block that touches several variables, but you cannot await inside it. SemaphoreSlim.WaitAsync is the async-friendly mutual exclusion or throttle. See Synchronization.

Part 6: DI and ASP.NET Core

47. What is dependency injection, and what are the three lifetimes? DI means a class receives its dependencies (usually as interfaces through the constructor) instead of creating them, and a container builds the object graph. Transient: a new instance every request for the service. Scoped: one instance per scope (per HTTP request in ASP.NET Core). Singleton: one instance for the application's life. A singleton must not depend on a scoped service (the "captive dependency" bug). See Dependency injection.

C# Service lifetimes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

48. What is middleware in ASP.NET Core? A component in the request pipeline: each piece receives the HttpContext, may do work before and after calling the next component, or short-circuit the request. Order matters: exception handling and HTTPS redirection come first, then routing, authentication, authorization and finally the endpoints. See Middleware.

C# Middleware order on a loopback server

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

49. Minimal APIs versus controllers? Minimal APIs map routes to lambdas or methods with little ceremony and have lower overhead; controllers (MVC) give conventions, filters, model-binding attributes and more structure for big APIs. Both use the same pipeline, routing, DI and model binding. See Minimal APIs and MVC and Razor.

50. How do you design a good REST API in ASP.NET Core? Use nouns for resources and HTTP verbs for actions, return correct status codes (201 with a Location header on create, 404, 409, 422/400 with ProblemDetails), validate input, version the API, paginate lists, make PUT/DELETE idempotent and pass CancellationToken into data access. See API design and Validation and problem details.

Bonus: two questions with code

What does this print, and why? Predict the output of the following program before you run it. It combines string immutability, ref and a captured variable, a pattern that interviewers love.

C# Predict the output

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The first call changes only the local copy of the reference; ref passes the variable itself. The array is a reference type, so Reset modifies the shared object.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A singleton service takes a scoped service in its constructor. What is the problem?

    A singleton lives for the whole application, so it keeps the first scoped instance forever. With scope validation on, the container throws instead.
  2. 2. What does throw; do differently from throw ex; inside a catch block?

    throw; rethrows the current exception with its stack trace intact. throw ex; resets the stack trace to the current line, hiding where the error began.
  3. 3. Which statement about async/await is true?

    await returns control to the caller and resumes later. Async I/O needs no thread while waiting, and async methods do not create threads by themselves.
  4. 4. In which case do lambdas created in a classic for loop all see the same final value?

    A for loop declares one counter variable for the whole loop, and closures capture the variable, not its value at the time. Copy it into a local inside the body to fix it.
  5. 5. Why should a Dictionary key be immutable?

    The entry is filed in a bucket by the hash at insertion time. If the key's hash later changes, lookups search the wrong bucket.

Summary

  • Know how a C# program flows: Roslyn to IL, JIT to native code, the generational GC cleaning up, and Dispose for unmanaged resources.
  • Be able to explain value versus reference semantics, boxing, string immutability and when a struct is the right choice.
  • Explain override versus new, abstract class versus interface, and what records give you.
  • Know LINQ's deferred execution, closure capture, and which collection fits which job.
  • Describe async/await as a state machine with no blocked thread, and avoid async void, .Result and unobserved failures.
  • Explain DI lifetimes and the middleware pipeline, and design APIs with correct status codes and cancellation.

You have reached the end of the C# tutorial. Revisit the cheat sheet and the practice problems whenever you need a refresher, then build something real: a project is the best interview you can give yourself.