These are the C# and .NET questions that come up in technical interviews today, from junior screens to senior rounds. Each answer is short enough to say out loud, with code only where it makes the point faster. Answers assume .NET 8 or later and modern C#.
Language basics
What is C# and how does the code run?
C# is a statically typed, object-oriented language with strong functional features. The Roslyn compiler turns source code into Intermediate Language (IL) stored in an assembly. At run time the CLR’s JIT compiler translates IL to machine code, method by method. With Native AOT, the whole app is compiled to machine code ahead of time instead, which gives faster startup at the cost of some reflection and dynamic code features.
What is the difference between managed and unmanaged code?
Managed code runs under the CLR, which handles memory allocation, garbage collection, type safety and exception handling. Unmanaged code runs directly on the operating system: C and C++ libraries, Win32 APIs and COM components. C# calls into unmanaged code through P/Invoke or COM interop, and any unmanaged resource it acquires (file handles, sockets, native memory) has to be released explicitly, usually through IDisposable.
What is the difference between == and Equals()?
For reference types, == compares references unless the type overloads the operator. Equals is a virtual method that types override to compare content. string does both, which is why the confusion persists. The catch is that operators are resolved at compile time from the static type, while Equals is dispatched at run time:
object a = new string('x', 3);
object b = new string('x', 3);
Console.WriteLine(a == b); // False: object's == compares references
Console.WriteLine(a.Equals(b)); // True: string overrides Equals
Console.WriteLine((string)a == (string)b); // True: string overloads ==
For value types, Equals compares field values. Records generate both == and Equals with value semantics.
What is the difference between const and readonly?
A const is a compile-time constant and must be a primitive, string or null. Its value is copied into every assembly that uses it, so changing a public const in a library has no effect on callers until they are recompiled. A readonly field is assigned at run time, in its declaration or a constructor, and can hold any type. For values that might change between versions, prefer static readonly.
Why is Main static?
The runtime has to call the entry point before any object exists, so it cannot be an instance method. Since C# 9, top-level statements let you skip writing Main altogether; the compiler generates a static entry point for you.
Types and memory
What is the difference between value types and reference types?
A variable of a value type (int, DateTime, any struct or enum) holds the data itself, and assignment copies it. A variable of a reference type (class, string, arrays, delegates) holds a reference to an object on the managed heap, and assignment copies the reference, so both variables see the same object. “Value types live on the stack” is a simplification interviewers like to probe: a value-type local usually lives on the stack, but an int field of a class lives on the heap inside that object.
What is boxing, and why should you care?
Boxing wraps a value type in a heap object so it can be treated as object or an interface. Unboxing copies the value back out.
int n = 42;
object o = n; // boxing: allocates a new object and copies 42 into it
int m = (int)o; // unboxing: type check, then copy
Each box is an allocation the garbage collector has to clean up. Generic collections removed most of it, but it still sneaks in through object parameters and non-generic interfaces.
When do you use a struct, a class or a record?
Use a class for most types, especially ones with identity or mutable state. Use a struct for small, short-lived values (a point, a money amount) where avoiding a heap allocation matters; keep it immutable with readonly struct, because mutating a copy by accident is a classic bug. Use a record (C# 9) when the type is mainly data: the compiler generates value-based equality, ToString, deconstruction and support for with expressions. record is a class by default; record struct (C# 10) gives the same features on a value type.
var a = new Point(1, 2);
var b = new Point(1, 2);
Console.WriteLine(a == b); // True: records compare by value
var c = a with { Y = 5 }; // copy with one property changed
Console.WriteLine(c); // Point { X = 1, Y = 5 }
public record Point(int X, int Y);
Two corrections to answers that still circulate: since C# 10 a struct can declare its own parameterless constructor, and a struct can implement interfaces but cannot inherit from another type.
Why are strings immutable, and when do you use StringBuilder?
Every method that seems to change a string returns a new one, which makes strings safe to share between threads and to use as dictionary keys. Concatenating in a loop therefore creates a new string on every pass; use StringBuilder there. For a handful of pieces, + or interpolation is fine.
What is a jagged array?
An array whose elements are arrays, each of which can have a different length. It is declared with repeated brackets, int[][] jagged = new int[10][];, and each row is created separately. A multidimensional array, int[,] grid = new int[10, 10];, is a single rectangular block instead.
Object-oriented programming
What are the four principles of OOP?
Encapsulation hides internal state so the implementation can change without breaking callers. Abstraction exposes what an object does and hides how. Inheritance lets a derived class reuse and extend a base class. Polymorphism lets code work with a base type or interface while the actual object decides which implementation runs.
What is the difference between an interface and an abstract class?
An abstract class can hold state (fields), constructors and partial implementation, but a class can inherit from only one. An interface defines a contract, and a class can implement many. Since C# 8 interfaces can also contain default method implementations and static members, and since C# 11 static abstract members, which power generic math. Use an interface for a capability (IComparable<T>, IDisposable) and an abstract class when several types share real code and state.
What is the difference between virtual, abstract, override and new?
An abstract method has no body and must be overridden by any non-abstract derived class. A virtual method has a default implementation that a derived class may override. Both are resolved at run time from the object’s actual type. Marking a method new instead hides the base method: which one runs then depends on the compile-time type of the variable, which is rarely what anyone wants.
What is System.Object?
The base class of every type in .NET, including value types, which derive from it through System.ValueType. If you override its Equals, override GetHashCode too, or the type will misbehave as a dictionary key.
Generics and collections
Why use generics?
Generics give you type safety at compile time and avoid boxing. List<int> stores int values directly; the old ArrayList stores object, so every add boxes and every read needs a cast that can fail at run time. Constraints such as where T : IComparable<T> or where T : class, new() tell the compiler what operations T supports. The collections tutorial shows the main generic collections side by side.
Which collection would you use for fast lookups?
Dictionary<TKey, TValue> for key-value lookups and HashSet<T> for membership tests, both O(1) on average. List<T>.Contains is O(n). Both hash-based types depend on a correct GetHashCode: if a key’s hash changes after it is added, you will not find it again. For data shared between threads, use ConcurrentDictionary.
What does yield return do?
It turns a method into an iterator. The compiler generates a state machine that produces one item each time the caller asks for the next, so nothing runs until enumeration starts and the full sequence never has to exist in memory. See the yield keyword example.
LINQ
What is the difference between IEnumerable<T> and IQueryable<T>?
IEnumerable<T> LINQ methods take delegates and run in memory. IQueryable<T> methods take expression trees, which a provider such as Entity Framework Core translates into SQL. The difference shows when you mix them up:
// Filter runs in the database: WHERE IsActive = 1
var active = await db.Customers.Where(c => c.IsActive).ToListAsync();
// Every row is loaded first, then filtered in memory
IEnumerable<Customer> all = db.Customers;
var activeSlow = all.Where(c => c.IsActive).ToList();
What is deferred execution?
Most LINQ operators do not run when you call them. They build a query that executes when you enumerate it, with foreach, ToList(), Count() and similar.
List<int> numbers = [1, 2, 3];
IEnumerable<int> evens = numbers.Where(n => n % 2 == 0);
numbers.Add(4);
Console.WriteLine(string.Join(", ", evens)); // 2, 4
The trap is multiple enumeration: each pass re-runs the query, which for a database query means another round trip. Call ToList() once if you need the results more than once. The LINQ examples cover the common operators.
Async and threading
What is the difference between a Task and a Thread?
A Thread is an operating-system thread with its own stack; creating one is expensive. A Task represents an operation that will complete in the future. CPU work started with Task.Run runs on a thread-pool thread, and an I/O task, such as an HTTP request, uses no thread at all while it waits. In modern code you rarely create a Thread directly; the thread example shows the old approach.
What happens when you await a task?
If the task has not finished, the method returns to its caller and the rest of it is registered as a continuation. The compiler rewrites the method into a state machine to make this work. When the task completes, execution resumes after the await, on the captured synchronization context if there is one (the UI thread in WinForms or WPF), otherwise on a thread-pool thread. Exceptions are rethrown at the await.
How can async code deadlock?
The classic case is blocking on a task with .Result or .Wait() on a thread that has a single-threaded synchronization context:
private void LoadButton_Click(object sender, EventArgs e)
{
string text = GetTextAsync().Result; // blocks the UI thread
}
GetTextAsync wants to resume on the UI thread, but the UI thread is blocked waiting for it. Neither can proceed. The fix is to make the handler async and await the call. Library code can also use ConfigureAwait(false) so its continuations do not need the original context. ASP.NET Core has no synchronization context, so this exact deadlock does not occur there, but blocking still wastes threads and can starve the pool.
Why avoid async void?
The caller cannot await an async void method or catch its exceptions; an unhandled exception in one typically crashes the process. Use async Task everywhere except event handlers, where the signature is fixed.
How do you make code thread-safe?
Avoid shared mutable state where you can. Where you cannot, protect it with lock (on .NET 9 and later, preferably on a System.Threading.Lock instance), use Interlocked for simple counters, or use a concurrent collection. You cannot await inside a lock block; use SemaphoreSlim and WaitAsync for async code. Lazy<T> is the easiest thread-safe singleton, as the singleton example explains.
Exceptions and resources
How does exception handling work in C#?
Code that may fail goes in a try block, catch blocks handle specific exception types (most specific first), and a finally block runs whether or not an exception occurred. throw raises an exception. Exception filters (catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.NotFound)) let you catch only the cases you can handle. More detail in the try/catch/finally example.
What is the difference between throw; and throw ex;?
throw; rethrows the current exception and keeps its original stack trace. throw ex; resets the stack trace to the current line, which hides where the error actually happened. Inside a catch block, use throw; or wrap the exception as the InnerException of a new one.
What are IDisposable and using for?
The garbage collector frees memory but knows nothing about file handles, database connections or sockets. Types that hold such resources implement IDisposable, and using guarantees Dispose is called, even when an exception is thrown:
using var stream = File.OpenRead(path);
// stream.Dispose() runs when the enclosing scope ends
For async cleanup, types implement IAsyncDisposable and you write await using. A finalizer is only a safety net for unmanaged resources; most classes should not have one.
Modern C# features
What are nullable reference types?
With <Nullable>enable</Nullable> (the default in new projects), string means “never null” and string? means “may be null”. The compiler tracks null state through your code and warns when you might dereference null. It is a compile-time analysis only: nothing changes at run time, so values arriving from outside (JSON, reflection, older libraries) can still be null.
string name = null; // warning CS8600
string? nickname = null; // fine
Console.WriteLine(nickname.Length); // warning CS8602: possible null dereference
What is pattern matching?
Pattern matching tests a value’s shape and extracts parts of it in one expression. Combined with switch expressions it replaces long if/else chains:
static decimal Shipping(Order order) => order switch
{
{ Total: >= 100m } => 0m,
{ Country: "US" } => 5m,
{ Items.Count: > 10 } => 15m,
_ => 10m
};
This uses property patterns, relational patterns (C# 9) and extended property patterns (C# 10). C# 11 added list patterns such as [first, .., last].
What is Span<T> and why does it matter?
Span<T> is a view over a contiguous block of memory: part of an array, a string, stack memory or native memory. Slicing a span creates no copy and no allocation, which is why parsing and formatting code across .NET has moved to span-based APIs.
ReadOnlySpan<char> date = "2026-11-25";
int year = int.Parse(date[..4]);
int month = int.Parse(date.Slice(5, 2));
Span<T> is a ref struct, so it can only live on the stack: it cannot be a field of a class, be boxed or be held across an await. Use Memory<T> when you need to store it or use it in async code.
What are delegates, events and lambdas?
A delegate is a type-safe reference to a method; Func<> and Action<> cover most needs without declaring your own. A lambda is a concise way to create a delegate (or an expression tree). An event is a delegate field that outside code can only subscribe to and unsubscribe from, not invoke or overwrite. A long-lived publisher keeps its subscribers alive until they unsubscribe, a common leak. See the delegate and event example.
The .NET runtime
How does garbage collection work?
The .NET GC is generational. New objects go into generation 0, which is collected often and cheaply. Objects that survive move to generation 1 and then generation 2, which is collected rarely, because long-lived objects tend to stay alive. Objects of 85,000 bytes or more go on the Large Object Heap, which is collected with generation 2 and not compacted by default. Calling GC.Collect() yourself is almost always a mistake.
What is the difference between .NET Framework, .NET Core and .NET?
.NET Framework (last version 4.8.1) is Windows-only and receives only maintenance fixes. .NET Core was the cross-platform rewrite; from version 5 it is simply called .NET. Even-numbered releases such as .NET 8 and .NET 10 are long-term support; odd-numbered ones have a shorter support window. New projects should target a current .NET release.
What is dependency injection, and what are the service lifetimes?
Dependency injection means a class receives its dependencies through its constructor instead of creating them, which makes it testable and loosely coupled. ASP.NET Core and the generic host have a built-in container with three lifetimes:
builder.Services.AddSingleton<IClock, SystemClock>(); // one instance for the app
builder.Services.AddScoped<IOrderRepository, OrderRepository>(); // one per request (scope)
builder.Services.AddTransient<IEmailSender, SmtpEmailSender>(); // new instance every time
The usual follow-up is the captive dependency: a singleton that takes a scoped service, such as an EF Core DbContext, keeps that one instance forever. The container detects this in development and throws.
What is serialization?
Serialization converts an object into a format that can be stored or sent, such as JSON, XML or a binary protocol, and deserialization reverses it. In current .NET, System.Text.Json is the default for JSON. BinaryFormatter was insecure and has been removed as of .NET 9, so if an interviewer asks about it, say so. For XML, see the generic XML serialization example.