Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 77 ยท C, C++ and Systems Interview Questions

C# and .NET: CLR, Value Types, LINQ, async and Garbage Collection

Prepare C# and .NET interviews: the CLR and JIT, value versus reference types, boxing, LINQ deferred execution, async/await, IDisposable and garbage collection.

C# interviews mix language questions ("what is the difference between a struct and a class?") with platform questions ("what does the CLR do?"). The recurring themes are memory (value and reference types, boxing, garbage collection, IDisposable), LINQ (and why it is lazy), and async/await (the area where wrong answers are most common). If you can explain each with a short program, you will stand out from candidates who only recite definitions.

All examples run on the site's C# 14 / .NET 10 runner (top-level statements, no NuGet packages). Remember the C# rule that top-level statements must come before type declarations, which is why some programs below define their types at the bottom. The complete lessons are in the C# tutorial and C# Reference. For the equivalent topics in another managed language, compare Java Memory and JVM Questions.

From source code to running program

C# source Compiled by Roslyn.
CIL in an assembly A .dll or .exe with metadata.
JIT compiler The CLR turns CIL into machine code.
Runtime services Garbage collection, type safety, threads.

.NET also supports ahead-of-time compilation for fast startup.

1 / 2

What are the CLR, CIL and the JIT?

Short answer: The CLR (Common Language Runtime) is the .NET execution engine. The C# compiler (Roslyn) does not produce machine code; it produces CIL (Common Intermediate Language, also called MSIL) stored in an assembly together with metadata. At run time the CLR's JIT (just-in-time) compiler translates each method to native code the first time it is called, then reuses it. The CLR also provides memory management (the garbage collector), type safety checks, exception handling and threading. The CTS (Common Type System) defines the types all .NET languages share, which is why C#, F# and Visual Basic can use each other's libraries.

Modern .NET adds tiered compilation (a quick first JIT, then re-optimization of hot methods) and Native AOT (compile to a native executable ahead of time, giving faster startup but fewer dynamic features such as reflection emit).

Value types versus reference types

Short answer: A value type (int, double, bool, struct, enum) holds its data directly and is copied on assignment. A reference type (class, string, arrays, delegates, record) holds a reference to an object on the managed heap, so assignment copies the reference and both variables see the same object. Value types in a local variable usually live on the stack, but a value type inside a class lives with that object on the heap, so "structs live on the stack" is an oversimplification.

Boxing is converting a value type to object (or an interface): the runtime allocates a heap object and copies the value in. Unboxing copies it back and requires the exact original type. Boxing costs allocations, which is why generic collections (List<int>) replaced the old ArrayList.

Choose a struct for small, immutable, short-lived values (a point, a coordinate); choose a class for anything with identity, inheritance or larger state. Strings are reference types but immutable: every modification creates a new string, so build large text with StringBuilder.

C# Copy semantics, boxing and string immutability

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.

How does garbage collection work, and what is IDisposable for?

Short answer: The garbage collector (GC) frees objects that can no longer be reached from any root (static fields, local variables, CPU registers). It is generational: new objects start in generation 0; survivors are promoted to generation 1, then generation 2. Because most objects die young, collecting generation 0 is cheap. Objects of 85,000 bytes or more go to the Large Object Heap, which is collected with generation 2.

The GC only manages memory. Unmanaged resources (file handles, sockets, database connections) need deterministic cleanup, which is what IDisposable and the using statement are for: using calls Dispose() when the block ends, even if an exception is thrown. A finalizer (~Class) is a safety net that runs at an unpredictable time, never a replacement for Dispose.

C# using, generations and records

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.

Notice that close file-1 appears exactly when the block ends, not when the GC happens to run. Also notice the record: it is a reference type with value-based equality and a non-destructive with expression, which makes it a good fit for immutable data.

Why is LINQ lazy, and what is deferred execution?

Short answer: Most LINQ operators (Where, Select, OrderBy) do not run when you write them; they build a query that runs when you enumerate it (foreach, ToList, Count, First). This is deferred execution. It lets the query see the latest data and avoids unnecessary work, but it also means a query enumerated twice runs twice, and a captured variable or the source collection changing in between changes the result. Call ToList() or ToArray() to take a snapshot.

C# Deferred execution 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.

Two more LINQ points interviewers like: IEnumerable<T> queries run in memory, while IQueryable<T> (used by Entity Framework) builds an expression tree that a provider translates to SQL, so calling ToList() too early pulls the whole table into memory. And First() throws if there is no match, while FirstOrDefault() returns default.

How does async/await work?

Short answer: async and await let a method wait for slow work (I/O, timers) without blocking a thread. The compiler rewrites an async method into a state machine. At each await, if the awaited task is not finished, the method returns to its caller, and the rest of the method becomes a continuation that runs when the task completes. A Task is a promise of a future result; Task<T> carries a value. await unwraps the result and rethrows the original exception.

The questions behind the question:

  • Async is not threads. Waiting for I/O uses no thread at all. Task.Run is for CPU-bound work that should move to the thread pool.
  • Concurrency: start tasks first, then await Task.WhenAll(...). Awaiting each one in turn runs them sequentially.
  • Deadlocks: calling .Result or .Wait() on a task in a context with a single thread (older UI and ASP.NET frameworks) can deadlock, because the continuation needs the thread you are blocking. Prefer await all the way; library code often uses ConfigureAwait(false).
  • async void should only be used for event handlers, because exceptions in it cannot be caught by the caller.
  • Cancellation uses a CancellationToken passed down to the operations.
C# WhenAll, exceptions and cancellation

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.

Quick answers for the follow-ups

  • const versus readonly: const is a compile-time constant baked into callers; readonly is assigned at run time (declaration or constructor).
  • ref, out, in: pass by reference; out must be assigned by the callee; in is read-only by reference.
  • Delegates and events: a delegate is a type-safe function pointer; an event restricts it so only the owner can invoke it, and outside code can only subscribe (+=) or unsubscribe (-=).
  • Interface versus abstract class: an interface defines a contract (and since C# 8, default methods); an abstract class can hold state and shared implementation, and a class has only one base class but many interfaces.
  • Nullable reference types: with #nullable enable the compiler warns about possible null dereferences, turning many NullReferenceExceptions into compile-time warnings.
  • Dependency injection is built into ASP.NET Core with three lifetimes: transient (new each time), scoped (per request), and singleton.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

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

    Roslyn compiles C# to CIL. The CLR's JIT compiles each method to native code the first time it is called.
  2. 2. A struct is assigned to a second variable and the second is modified. What happens to the first?

    Value types are copied on assignment. Classes copy the reference, so both variables would see the change.
  3. 3. A LINQ query is defined, then an element is added to the source list, then the query is enumerated. What does the query return?

    Deferred execution means the query runs when enumerated, so it sees the current contents. ToList() would have taken a snapshot.
  4. 4. Which is the best way to run two independent async operations concurrently and wait for both?

    Starting both before awaiting lets them overlap; WhenAll completes when both finish and surfaces exceptions.
  5. 5. What is using (or a using declaration) for?

    using ensures Dispose runs at the end of the scope, releasing unmanaged resources promptly instead of waiting for the GC.

Summary

  • C# compiles to CIL; the CLR's JIT turns it into native code, and also provides the garbage collector and type safety.
  • Value types are copied, reference types share one object; boxing allocates and unboxing needs the exact type; strings are immutable.
  • The generational GC manages memory only; use IDisposable and using for files, sockets and connections.
  • LINQ is deferred: it runs on enumeration, so use ToList() for a snapshot; IQueryable is translated to SQL by the provider.
  • async/await frees threads while waiting; start tasks first, use Task.WhenAll, avoid .Result and async void.

Next: HTML and CSS Questions, where the language round gives way to the web platform.