.NET Core and C# interview questions and answers
Questions for .NET Core and C# interviews, from fresher basics such as the CLR, garbage collection and value types to the production problems interviewers ask experienced developers about. Each answer explains the why and shows a short example.
Mixed · 45 questions · Tap a question to see the answer.
Q1. A legacy ASP.NET (.NET Framework) app hangs when a controller calls
GetDataAsync().Result. Why, and how do you fix it?Classic ASP.NET and UI apps have a SynchronizationContext that lets only one thread run the request at a time.
.Resultblocks that thread while the awaited task wants to resume on the same context, so each waits for the other: a deadlock.Fix it by going async all the way: make the action
async Task<IActionResult>andawaitthe call. In library code that never needs the context,ConfigureAwait(false)also avoids the deadlock. ASP.NET Core has no SynchronizationContext, so this exact hang does not occur there, but blocking on tasks still wastes thread-pool threads and should be avoided.public async Task<IActionResult> Index() { var data = await _service.GetDataAsync(); return View(data); }Q2. What is the difference between
IEnumerable<T>andIQueryable<T>when querying a database with EF Core?IQueryable<T>builds an expression tree that EF Core translates to SQL, soWhere,OrderByandTakerun in the database and only matching rows come back.Once you switch to
IEnumerable<T>(for example withAsEnumerable()orToList()), later operators run in memory on rows already loaded. Filtering afterToList()on a large table loads the whole table first. Keep filters on theIQueryableand materialize at the end.// Good: WHERE and TOP run in SQL var recent = await db.Orders .Where(o => o.CreatedAt > since) .OrderByDescending(o => o.CreatedAt) .Take(50) .ToListAsync();Q3. When would you use a
recordinstead of aclassin C#?Use a
recordfor data whose identity is its values: DTOs, messages, events, value objects. Records give value-based equality, a readableToString(), deconstruction and non-destructive mutation withwith.Use a
classfor entities with identity and behaviour that change over time, such as an EF Core entity tracked by id.record structis available when you want value semantics without a heap allocation.public record Money(decimal Amount, string Currency); var a = new Money(10, "USD"); var b = a with { Amount = 20 }; Console.WriteLine(a == new Money(10, "USD")); // TrueQ4. Explain Singleton, Scoped and Transient lifetimes, and the bug caused by injecting a Scoped service into a Singleton.
Singleton: one instance for the app's lifetime. Scoped: one instance per scope, which in ASP.NET Core means per HTTP request. Transient: a new instance every time it is resolved.
If a Singleton takes a Scoped service (such as a
DbContext) in its constructor, that scoped instance is captured forever and shared across requests and threads. This is a 'captive dependency'. With aDbContextit causes threading errors and stale data. ASP.NET Core's scope validation throws at startup in Development to catch it. Fix it by making the consumer Scoped or by creating a scope withIServiceScopeFactorywhen needed.public class Worker(IServiceScopeFactory scopes) : BackgroundService { protected override async Task ExecuteAsync(CancellationToken ct) { using var scope = scopes.CreateScope(); var db = scope.ServiceProvider.GetRequiredService<AppDbContext>(); // use db for this unit of work } }Q5. Why is building a large string with
+=in a loop slow, and what should you use?Strings are immutable, so every
+=allocates a new string and copies everything so far. For n appends this is roughly O(n²) work and creates lots of garbage.Use
StringBuilderfor loops,string.Joinfor joining a collection, or string interpolation for a fixed number of parts.var sb = new StringBuilder(); foreach (var line in lines) sb.AppendLine(line); var text = sb.ToString();Q6. What does
IDisposabledo, and why shouldHttpClientusually not be wrapped inusingper request?IDisposablereleases unmanaged resources (sockets, file handles) deterministically;usingcallsDisposeat the end of the scope.HttpClientis the exception that proves the rule: creating and disposing one per request can exhaust sockets because connections linger in TIME_WAIT. Reuse clients throughIHttpClientFactory(typed or named clients) or a long-lived instance withSocketsHttpHandler.PooledConnectionLifetimeset so DNS changes are picked up.builder.Services.AddHttpClient<GitHubClient>(c => c.BaseAddress = new Uri("https://api.github.com/"));Q7. You need data from three independent APIs. How do you call them in parallel, and how are exceptions reported?
Start all three tasks first, then
await Task.WhenAll(...). Total time is roughly the slowest call instead of the sum.If several tasks fail,
awaitrethrows only the first exception; the full set is in the returned task'sException.InnerExceptions. Pass aCancellationTokenso the others can stop when one fails if that is what you need.var userTask = api.GetUserAsync(id, ct); var ordersTask = api.GetOrdersAsync(id, ct); var prefsTask = api.GetPrefsAsync(id, ct); await Task.WhenAll(userTask, ordersTask, prefsTask); var user = userTask.Result; // already completed, safeQ8. What do nullable reference types (
string?) change at runtime?Nothing at runtime. They are a compile-time feature: with
<Nullable>enable</Nullable>the compiler tracks whether a reference may be null and warns on likely null dereferences.stringmeans 'should not be null' andstring?means 'may be null'. The!operator silences a warning but adds no check, so you still validate external input, for example withArgumentNullException.ThrowIfNull.Q9. What is the difference between value types and reference types, and when would you make a
struct?Value types (
int,DateTime,struct) hold their data directly and are copied on assignment. Reference types (class,string, arrays) are stored on the heap and variables hold a reference, so two variables can point at the same object.Make a
structfor small, immutable values that are created in large numbers, such as a point or a money amount, where avoiding heap allocations helps. Preferreadonly struct. Large or mutable structs are a trap because every copy duplicates the data and changes to a copy are lost.Q10. How do you let a long-running operation stop when the HTTP client disconnects in ASP.NET Core?
Accept a
CancellationTokenparameter in the action. ASP.NET Core binds it toHttpContext.RequestAborted, which is cancelled when the client disconnects.Pass that token down to every async call (EF Core queries,
HttpClient, delays) so work stops early and resources are freed.[HttpGet("report")] public async Task<IActionResult> Report(CancellationToken ct) { var rows = await db.Sales.Where(s => s.Year == 2026).ToListAsync(ct); return Ok(rows); }Q11. What is
Span<T>and what problem does it solve?Span<T>is a type-safe view over a contiguous block of memory (an array, a stack buffer or native memory) without copying it. Slicing a span is free, so parsing code can work on parts of a buffer without allocating substrings or sub-arrays.It is a
ref struct, so it can only live on the stack: no fields in classes, no capture in lambdas, and no use acrossawait. UseMemory<T>when you need to store it or use it in async code.ReadOnlySpan<char> line = "2026-10-16,42"; int comma = line.IndexOf(','); int value = int.Parse(line[(comma + 1)..]); // no substring allocatedQ12. What is the difference between .NET LTS and STS releases, and which should a production team pick?
Even-numbered releases (.NET 8, .NET 10) are Long Term Support with 3 years of patches. Odd-numbered releases (.NET 9, .NET 11) are Standard Term Support. Microsoft extended STS support to 24 months starting with .NET 9.
Most production teams standardise on LTS and upgrade every two years. STS suits teams that want new features early and can upgrade on schedule. Either way, install the monthly servicing updates, because they contain security fixes.
Q13. What is the difference between .NET (formerly .NET Core) and .NET Framework?
.NET Framework is the original Windows-only runtime. It gets security fixes but no new features, and its last version is 4.8.1. .NET (called .NET Core up to version 3.1, then just .NET from version 5) is the cross-platform, open-source successor that runs on Windows, Linux and macOS.
New projects should use modern .NET: it is faster, supports containers and side-by-side installs, and gets a new major version every November. .NET Framework is still used for older apps that depend on Windows-only technologies such as Web Forms or WCF server.
Q14. What do the CLR, IL and the JIT compiler do when a .NET program runs?
The C# compiler turns your code into Intermediate Language (IL) stored in a .dll. At run time the Common Language Runtime (CLR) loads that IL, and the Just-In-Time (JIT) compiler turns each method into native machine code the first time it is called.
The CLR also provides garbage collection, type safety, exception handling and threading. Tiered compilation first produces quick, simple code and recompiles hot methods with more optimisation later. Native AOT is an alternative that compiles everything ahead of time for faster startup and smaller memory use, with some limits on reflection.
Q15. How does garbage collection work in .NET, and what are generations?
The garbage collector (GC) frees objects that nothing references any more. The managed heap is split into generations: new objects go into generation 0, objects that survive a collection move to generation 1 and then generation 2. Most objects die young, so collecting gen 0 often is cheap.
Objects of 85,000 bytes or more go on the Large Object Heap, which is collected with gen 2. To help the GC: avoid creating many short-lived large objects, reuse buffers (for example with
ArrayPool<T>), and do not callGC.Collect()in normal code.Q16. What is boxing and unboxing, and why can it hurt performance?
Boxing happens when a value type, such as an
int, is converted toobjector to an interface: the runtime copies the value into a new object on the heap. Unboxing copies it back out. Each box is an extra allocation that the GC later has to clean up.It often happens by accident with old non-generic collections like
ArrayList, or with string formatting of value types. Generic collections such asList<int>avoid it because they store the values directly.object o = 42; // boxing: allocates int n = (int)o; // unboxing: copies the value back var list = new List<int> { 1, 2, 3 }; // no boxingQ17. What is the difference between an abstract class and an interface in C#?
An abstract class is a base class that cannot be created on its own. It can hold fields, constructors and both finished and abstract methods, and a class can inherit from only one of them.
An interface describes a contract that any class or struct can implement, and a type can implement many interfaces. Since C# 8 an interface can have default method implementations, but it still cannot hold instance fields. Use an interface for a capability shared by unrelated types (for example
IComparable), and an abstract class when related types share real code and state.Q18. What do the access modifiers public, private, protected, internal and protected internal mean?
publicis visible everywhere.privateis visible only inside the same type, and is the default for class members.protectedis visible in the type and in classes that inherit from it.internalis visible anywhere in the same assembly (project).protected internalmeans the same assembly OR derived classes.private protectedmeans derived classes that are also in the same assembly. Keep members as private as you can and widen them only when needed.Q19. What does the static keyword mean on a class, a field and a method?
A static member belongs to the type itself, not to any object, so there is one copy shared by all callers. A static method cannot use
thisor instance fields. A static class cannot be created withnewand can contain only static members; it is often used for helpers and extension methods.Be careful with static mutable fields in web apps: they are shared by every request and every thread, so they need locking or should be replaced with a registered service.
Q20. What is the difference between ref, out and in parameters?
refpasses a variable by reference: the method can read and change the caller's variable, and it must be assigned before the call.outis also by reference, but the method must assign it before returning, which is why it is used by methods likeint.TryParse.inpasses by reference but read-only. It can avoid copying a large struct, though for small structs passing by value is just as fast.if (int.TryParse("42", out var n)) Console.WriteLine(n + 1); void Double(ref int x) => x *= 2; int v = 5; Double(ref v); // v is now 10Q21. What is the difference between == and Equals, and why override GetHashCode with Equals?
For reference types,
==checks by default whether two variables point to the same object, unless the type overloads the operator (asstringdoes).Equalscan be overridden to compare values. Records generate value-based equality for you.If you override
Equals, you must overrideGetHashCodeso that equal objects return the same hash code. OtherwiseDictionaryandHashSetwill fail to find items that are equal.Q22. What is the difference between const and readonly?
constvalues are fixed at compile time and copied into every assembly that uses them, so they can only be simple types such as numbers and strings.readonlyfields are set at run time, in the declaration or the constructor, and can hold any type.Because a
constis copied into other assemblies, changing it needs those assemblies to be rebuilt. Useconstfor values that never change (such as the number of days in a week) andstatic readonlyfor configuration-like values.Q23. What are good practices for throwing and catching exceptions in .NET?
Catch only exceptions you can handle, as close as possible to where you can do something useful, and let the rest reach a global handler that logs them. Use
throw;rather thanthrow ex;when rethrowing, so the original stack trace is kept.Do not use exceptions for normal control flow: prefer
TryParsestyle methods for expected failures. Clean up withusingorfinally, and add useful context when wrapping an exception by passing the original as the inner exception.try { await SaveAsync(order, ct); } catch (DbUpdateConcurrencyException ex) { logger.LogWarning(ex, "Order {Id} changed by someone else", order.Id); throw; // keeps the stack trace }Q24. What are generics, and what are generic constraints used for?
Generics let you write a class or method once and use it with many types while staying type-safe, for example
List<T>orRepository<T>. They avoid casts and boxing.Constraints limit which types can be used, so the code can rely on what the type supports:
where T : class(reference type),where T : struct,where T : new()(has a parameterless constructor),where T : IEntity(implements an interface) orwhere T : notnull.public T Max<T>(T a, T b) where T : IComparable<T> => a.CompareTo(b) >= 0 ? a : b;Q25. What are extension methods and when are they useful?
An extension method is a static method in a static class whose first parameter has the
thiskeyword. It can be called as if it were an instance method of that type, without changing the type. LINQ methods such asWhereandSelectare extension methods onIEnumerable<T>.They are useful for small helpers on types you do not own, and for setting up services (
builder.Services.AddMyFeature()). They cannot access private members, so they are not a way to change a class's behaviour.public static class StringExtensions { public static bool IsBlank(this string? s) => string.IsNullOrWhiteSpace(s); } if (name.IsBlank()) { /* ... */ }Q26. What is deferred execution in LINQ, and what bug can it cause?
Most LINQ operators such as
WhereandSelectdo not run when you write them. They build a query that runs each time you enumerate it, for example in aforeachor when you callToList().If you enumerate the same query twice, the work runs twice, and against a database that means two SQL queries. If the source changes in between, the results differ. Call
ToList()orToArray()once when you need a fixed result to reuse.var active = users.Where(u => u.IsActive); // nothing runs yet var count = active.Count(); // runs the filter var first = active.First(); // runs it again var list = active.ToList(); // run once, then reuse listQ27. Why should you avoid async void methods?
An
async voidmethod cannot be awaited, so the caller does not know when it finishes, and exceptions thrown inside it cannot be caught by the caller. They are raised on the synchronization context and can crash the process.Use
async Taskinstead. The only normal use ofasync voidis event handlers, such as a button click in a desktop app, and even there the body should catch its own exceptions.Q28. How do you make shared data thread-safe in C#?
Protect shared mutable state so only one thread changes it at a time. The
lockstatement does this for simple cases. For counters,Interlocked.Incrementis lighter. For shared collections, use the concurrent collections such asConcurrentDictionary<TKey, TValue>.You cannot
awaitinside alock. For async code, useSemaphoreSlimwithWaitAsync. The best option is often to avoid shared mutable state altogether, for example by using immutable objects or by giving each request its own data.private readonly SemaphoreSlim _gate = new(1, 1); public async Task RefreshAsync(CancellationToken ct) { await _gate.WaitAsync(ct); try { await LoadAsync(ct); } finally { _gate.Release(); } }Q29. How does pattern matching with switch expressions make C# code simpler?
Pattern matching lets you test the type and shape of a value and pull out its parts in one step. A switch expression returns a value for the first matching pattern and the compiler warns you when a case is missing.
It replaces long chains of
if/elsewith casts, and works with type patterns, property patterns, relational patterns such as> 100andand/orcombinations.decimal Shipping(Order o) => o switch { { Total: >= 1000 } => 0m, { Country: "IN" } => 49m, { IsExpress: true } => 299m, _ => 99m, };Q30. What are the SOLID principles, with a short example of one?
SOLID is five design guidelines: Single responsibility (a class has one reason to change), Open/closed (extend behaviour without editing existing code), Liskov substitution (a derived class must work wherever its base class does), Interface segregation (small, focused interfaces) and Dependency inversion (depend on abstractions, not concrete classes).
Example of dependency inversion: an
OrderServicetakes anIEmailSenderin its constructor instead of creatingSmtpEmailSenderitself. ASP.NET Core dependency injection then supplies the real sender, and tests can pass a fake one.Q31. What is a delegate, and how is an event different from a public delegate field?
A delegate is a type-safe reference to a method: it stores which method to call (and the target object), so you can pass behaviour around like data.
Func<T>,Action<T>andPredicate<T>are the built-in generic delegates.An
eventis a delegate with restricted access. Outside the declaring class, code can only subscribe (+=) or unsubscribe (-=); it cannot invoke the event or replace all subscribers with=. That protects the publisher and other subscribers.A common leak: a short-lived object subscribes to an event on a long-lived object and never unsubscribes, so the long-lived object keeps it alive.
public class Order { public event EventHandler<decimal>? Paid; public void Pay(decimal amount) => Paid?.Invoke(this, amount); } order.Paid += (_, amount) => Console.WriteLine($"Paid {amount}");Q32. What is the difference between Func, Action and Predicate?
All three are generic delegate types.
Action<T1..T16>takes parameters and returns nothing.Func<T1..T16, TResult>takes parameters and returns a value; the last type argument is the return type.Predicate<T>takes one value and returnsbool.LINQ uses
Func, for exampleWhere(Func<T, bool>).Predicate<T>appears in older APIs such asList<T>.Find. In new codeFunc<T, bool>is the usual choice.Action<string> log = msg => Console.WriteLine(msg); Func<int, int, int> add = (a, b) => a + b; Predicate<int> isEven = n => n % 2 == 0;Q33. What does yield return do, and when is it useful?
yield returnturns a method into an iterator. The compiler builds a state machine, and each value is produced only when the caller asks for the next item, so the method runs lazily.It is useful for streaming large or endless sequences without building a whole list in memory, such as reading a big file line by line. Remember that the code runs again every time the sequence is enumerated, and exceptions appear during enumeration, not when the method is called.
IEnumerable<string> ReadLines(string path) { using var reader = new StreamReader(path); while (reader.ReadLine() is { } line) yield return line; }Q34. What is the difference between Task and ValueTask, and when should you use ValueTask?
Taskis a class, so every returned task is a heap allocation (some common results are cached).ValueTaskis a struct that can wrap either a result or aTask, so a method that usually completes synchronously, for example from a cache, can return without allocating.Use
ValueTaskonly on hot paths where that saving is measured. It has rules: await it only once, do not await it concurrently, and do not call.Resulton it before it completes. If you need to do any of that, call.AsTask(). For most application code,Taskis the right default.Q35. What does ConfigureAwait(false) do, and do you need it in ASP.NET Core?
By default,
awaitresumes on the captured synchronization context, such as the UI thread in WPF or WinForms.ConfigureAwait(false)says the rest of the method can run on any thread-pool thread.ASP.NET Core has no synchronization context, so in application code there it makes no difference. It still matters in general-purpose libraries, which may be called from UI apps or old ASP.NET, where it avoids deadlocks and extra thread switches. In UI code, do not use it before touching UI controls.
Q36. What is the difference between a Thread and a Task?
A
Threadis an operating-system thread that you create and manage yourself; it is expensive to create and holds about 1 MB of stack.A
Taskrepresents an operation that will complete in the future. CPU work started withTask.Runruns on the shared thread pool, and I/O work such as an HTTP call uses no thread at all while it waits. Tasks also support results, exceptions, cancellation andawait.Use tasks and async/await for almost everything. Create a dedicated thread only for rare long-running, blocking work, for example with
TaskCreationOptions.LongRunning.Q37. Why is looking up an item in a Dictionary faster than in a List?
List<T>.ContainsorFindchecks items one by one, which is O(n).Dictionary<TKey,TValue>andHashSet<T>use the key's hash code to jump to a bucket, so lookups are O(1) on average.That only works if
GetHashCodeandEqualsare implemented consistently and the key is not changed while it is in the dictionary. For many lookups against a large list, build a dictionary or hash set once and look up in it.var byId = customers.ToDictionary(c => c.Id); if (byId.TryGetValue(42, out var customer)) Console.WriteLine(customer.Name);Q38. Strings in .NET are immutable. What does that mean in practice?
A
stringobject never changes after it is created. Methods such asReplace,ToUpperor+return a new string and leave the original unchanged, so you must use the returned value.Immutability makes strings safe to share between threads and to use as dictionary keys. The cost is that many small modifications create many objects, which is why loops that build text should use
StringBuilder, and whystring.Equals(a, b, StringComparison.OrdinalIgnoreCase)is better than comparingToLower()copies.Q39. What is the difference between virtual/override and the new keyword on a method? What does sealed do?
virtualallows a derived class tooverridea method, and the override runs even when the object is used through a base-class reference. That is polymorphism.newhides the base method instead. Which method runs then depends on the variable's declared type, not the real object, which surprises people and is rarely what you want.sealedon a class stops anyone deriving from it;sealed overrideon a method stops further overriding. Sealing classes that are not designed for inheritance is a good default and can also let the JIT optimise calls.class Animal { public virtual string Speak() => "..."; } class Dog : Animal { public override string Speak() => "Woof"; } Animal a = new Dog(); Console.WriteLine(a.Speak()); // WoofQ40. What do the init and required keywords do on properties?
An
initaccessor lets a property be set only during object creation, in an object initializer or constructor, which makes immutable objects easy to create.required(C# 11) makes the compiler insist that callers set the property in the object initializer, so you cannot forget an important value even without a constructor. Together they give safe, immutable DTOs and options classes.public class CreateUser { public required string Email { get; init; } public string? DisplayName { get; init; } } var cmd = new CreateUser { Email = "[email protected]" }; // compile error without EmailQ41. What are primary constructors on classes (C# 12), and what should you watch out for?
A primary constructor puts the parameters right after the class name. The parameters are in scope in the whole class body, which removes the boilerplate of private fields assigned in a constructor, and suits dependency injection.
Watch out: the parameters are not readonly fields. They can be reassigned inside the class, and if you also copy one into a property, you may end up with two copies of the value. Assign to a
private readonlyfield when you need that guarantee.public class OrderService(IOrderRepository repo, ILogger<OrderService> logger) { public Task<Order?> GetAsync(int id) { logger.LogInformation("Loading {Id}", id); return repo.FindAsync(id); } }Q42. What are collection expressions in C#?
Collection expressions (C# 12) use square brackets to create arrays, lists, spans and other collections with one syntax:
int[] a = [1, 2, 3];orList<string> names = [];. The spread element..copies another collection in.The compiler picks an efficient way to build the target type. C# 15 adds a
with(...)element at the start to pass constructor arguments, such as a capacity or a comparer.int[] first = [1, 2]; int[] second = [3, 4]; List<int> all = [..first, ..second, 5];Q43. What is IAsyncEnumerable<T>, and when would you use it?
IAsyncEnumerable<T>is a sequence whose items arrive asynchronously. You consume it withawait foreachand produce it with anasyncmethod that usesyield return.Use it to stream results as they come in, such as rows from a database, pages from an API or messages from a queue, without waiting for the whole set or blocking threads. ASP.NET Core can stream an
IAsyncEnumerableresponse as JSON, and EF Core queries can be consumed withAsAsyncEnumerable().async IAsyncEnumerable<Order> GetOrdersAsync([EnumeratorCancellation] CancellationToken ct = default) { for (int page = 1; ; page++) { var batch = await api.GetPageAsync(page, ct); if (batch.Count == 0) yield break; foreach (var o in batch) yield return o; } }Q44. What are covariance and contravariance in C# generics?
Covariance (
out T) lets you use a more specific type where a more general one is expected for things that only produce values: anIEnumerable<string>can be used as anIEnumerable<object>.Contravariance (
in T) is the opposite for things that only consume values: anAction<object>can be used where anAction<string>is needed, because anything that accepts an object accepts a string.It works only on interfaces and delegates, and only with reference types.
List<T>is not covariant because it both reads and writes items.IEnumerable<string> names = new List<string> { "a" }; IEnumerable<object> objects = names; // covariance Action<object> print = o => Console.WriteLine(o); Action<string> printString = print; // contravarianceQ45. What is the difference between var, object and dynamic?
varis compile-time type inference: the variable still has one fixed static type chosen by the compiler, with full IntelliSense and type checking.objectis the base type of everything. You can store anything in it, but you must cast to use the real members, and value types get boxed.dynamicturns off compile-time checking: member access is resolved at runtime, so typos become runtime exceptions. Use it only for interop, such as COM or truly dynamic data, and prefervareverywhere else.
Original questions written to explain concepts; not taken from any certification exam. Spotted a mistake? See our corrections policy.