Software Engineer | 50 questions | 2026
C# and .NET Interview Questions and Answers
C# and .NET interview questions for freshers 27
Q1FresherMost askedAnswerHideWhat is the CLR and how does a C# program run on .NET?
The Common Language Runtime (CLR) is the execution engine of .NET. It loads, verifies and runs managed code and provides memory management, type safety and exception handling.
Flow: C# source -> compiler (Roslyn) -> CIL (intermediate language) in a DLL or EXE with metadata. At runtime: the JIT compiler turns CIL into native machine code -> the CLR runs it.
What the CLR provides:
- Garbage collection and memory management.
- CTS (Common Type System) and CLS so languages like C#, F# and VB interoperate.
- Assembly loading, type checking, security boundaries and threading.
- Tiered JIT and optional ahead-of-time (ReadyToRun, Native AOT) to cut startup time.
Managed code runs under the CLR. Unmanaged code (native DLLs) runs outside it and is reached through P/Invoke.
What they are checking: Whether you understand the runtime beyond writing C# syntax
Q2FresherMost askedAnswerHideWhat is the difference between value types and reference types in C#?
Value types hold their data directly. Reference types hold a reference to an object on the managed heap.
| Value type | Reference type | |
|---|---|---|
| Examples | int, bool, double, struct, enum, DateTime | class, string, array, delegate, interface, record |
| Stored | Where declared (stack or inside the owning object) | Heap, variable holds a pointer |
| Assignment | Copies the value | Copies the reference |
| Default | Zero / false | null |
int a = 1; int b = a; b = 5;
Console.WriteLine(a); // 1, independent copies
var p = new Person { Name = "A" };
var q = p; q.Name = "B";
Console.WriteLine(p.Name); // B, same object
class Person { public string Name = ""; }
string is a reference type but behaves like a value because it is immutable. A value type inside a class lives on the heap with its owner. So "value types live on the stack" is only partly true.
What they are checking: Core memory model understanding, often the first question
Q3FresherMost askedAnswerHideWhat are boxing and unboxing? Why do they hurt performance?
Boxing converts a value type to object (or an interface), allocating a heap object to hold a copy. Unboxing takes the value back out and needs a cast you write yourself.
int i = 42;
object o = i; // boxing: heap allocation + copy
int j = (int)o; // unboxing: type check + copy
// long k = (long)o; // InvalidCastException: the box holds an int
Cost: each box allocates memory, which increases garbage collection work, and the cast adds a type check. Hidden boxing happens when:
- Using non-generic collections such as
ArrayList. - Passing a struct to a method taking
objector a non-constrained interface. - Calling
string.FormatorConsole.WriteLine("{0}", i)with value types in older style.
Avoid it with generics (List<int>), generic constraints (where T : IComparable<T>), and Span<T>.
What they are checking: Whether you can reason about hidden allocations
Q4FresherMost askedAnswerHideWhat is the difference between a class and a struct in C#?
A class is a reference type allocated on the heap. A struct is a value type copied on assignment.
| class | struct | |
|---|---|---|
| Type kind | Reference | Value |
| Inheritance | Yes (single) | No (interfaces only) |
| Default | null | All fields zeroed |
| Parameterless constructor | Yes | Allowed since C# 10 |
| Equality default | Reference | Field by field |
Use a struct when it is small (about 16 bytes) and stands for a single value (point, money, coordinates). It should also be immutable (cannot change after creation). Mutable structs cause surprising bugs because methods work on copies.
public readonly struct Point { public int X { get; } public int Y { get; } public Point(int x, int y) { X = x; Y = y; } }
public readonly record struct Money(decimal Amount, string Currency); // C# 10
Choose a class for everything else, including anything with identity or large state. Mutating a struct stored in a List<T> indexer does not compile, a typical trap.
What they are checking: Whether you choose a type kind on design and performance grounds
Q5FresherMost askedAnswerHideWhat is the difference between an interface and an abstract class in C#?
An interface defines a contract. An abstract class defines a partially implemented base with shared state.
| Interface | Abstract class | |
|---|---|---|
| Multiple inheritance | A class can implement many | Only one base |
| Fields | No instance state | Yes |
| Constructors | No | Yes |
| Members | Default interface methods allowed since C# 8 | Abstract and concrete |
| Access modifiers | Public by default | Any |
public interface IRepository<T> { T? Get(int id); void Add(T item); }
public abstract class Report {
public void Run() { Load(); Render(); } // template method
protected abstract void Load();
protected abstract void Render();
}
Use interfaces for capabilities and for dependency injection and mocking. Use an abstract class when derived types share state or a skeleton algorithm. You can combine both: an interface for consumers and an abstract base for convenience.
What they are checking: Whether you know when to pick each, with DI and testing in mind
Q6FresherMost askedAnswerHideExplain async and await in C#. What is a Task?
async/await lets you write asynchronous code that reads like synchronous code, freeing the thread while waiting for I/O.
A Task (or Task<T>) represents an ongoing operation that will complete later. await suspends the method without blocking the thread and resumes it when the task finishes. The compiler turns the method into a state machine.
using var http = new HttpClient();
string html = await GetLengthAsync(http);
Console.WriteLine(html);
static async Task<string> GetLengthAsync(HttpClient http)
{
string body = await http.GetStringAsync("https://example.com"); // thread is released here
return $"Length: {body.Length}";
}
Key points:
- Async is about scalability for I/O-bound work (database, HTTP, files), not about making CPU work faster. For CPU-bound work use
Task.Run. - Return
Task, notvoid, so callers can await and observe exceptions. - Name methods with the
Asyncsuffix. - Exceptions are thrown at the
awaitpoint.
What they are checking: The most asked C# topic: whether you understand it conceptually and not just the keywords
Q7FresherMost askedAnswerHideExplain LINQ deferred execution with an example.
Most LINQ operators such as Where and Select do not run when you write them. They build a query that executes only when you enumerate it (foreach, ToList(), Count(), First()).
var numbers = new List<int> { 1, 2, 3 };
var query = numbers.Where(n => n > 1); // nothing executed yet
numbers.Add(10); // source changes
Console.WriteLine(string.Join(",", query)); // 2,3,10 (runs now, sees 10)
var snapshot = numbers.Where(n => n > 1).ToList(); // immediate execution
numbers.Add(20);
Console.WriteLine(snapshot.Count); // 3, unaffected
Consequences:
- The query always sees the latest data at enumeration time.
- Enumerating twice runs it twice, which can mean two database calls or repeated side effects. Materialise with
ToList()when you need a stable result. - Immediate operators:
ToList,ToArray,Count,Sum,First,Any. - With EF Core, a deferred query held past the
DbContextlifetime throws on enumeration.
What they are checking: Whether you know when LINQ actually runs
Q8FresherMost askedAnswerHideWhat is the difference between IEnumerable and IQueryable?
IEnumerable<T> runs queries in memory using delegates. IQueryable<T> builds an expression tree that a provider (EF Core) translates into SQL and runs at the data source.
// IQueryable: filtering becomes SQL: SELECT ... WHERE Price > 100
IQueryable<Product> q = db.Products.Where(p => p.Price > 100);
// IEnumerable: AsEnumerable() switches to memory, loading ALL products first
IEnumerable<Product> bad = db.Products.AsEnumerable().Where(p => p.Price > 100);
| IEnumerable | IQueryable | |
|---|---|---|
| Executes | In process | In the data source |
| Lambdas | Func<T,bool> | Expression<Func<T,bool>> |
| Use for | In-memory collections | Database queries |
Pitfalls: returning IQueryable from a repository leaks database details to the caller. Also, a C# method that EF cannot translate to SQL may throw an error or silently run in memory instead. Keep filtering, sorting and paging on IQueryable, and call ToListAsync() last.
What they are checking: Whether you know where filtering runs, which decides performance
Q9FresherMost askedAnswerHideWhat is dependency injection in ASP.NET Core and what are the service lifetimes?
DI is built into ASP.NET Core. You register services with a lifetime, and the container creates and injects them through constructors.
- Transient: a new instance every time it is requested. For lightweight, stateless services.
- Scoped: one instance per scope, which is one HTTP request. Used for
DbContextand unit-of-work style services. - Singleton: one instance for the app lifetime. Must be thread safe.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddTransient<IEmailBuilder, EmailBuilder>();
builder.Services.AddScoped<IOrderService, OrderService>();
builder.Services.AddSingleton<IClock, SystemClock>();
var app = builder.Build();
app.MapGet("/", (IOrderService s) => s.Hello());
app.Run();
public interface IEmailBuilder {} public class EmailBuilder : IEmailBuilder {}
public interface IOrderService { string Hello(); }
public class OrderService : IOrderService { public string Hello() => "hi"; }
public interface IClock {} public class SystemClock : IClock {}
.NET 8 also adds keyed services (AddKeyedSingleton, [FromKeyedServices("x")]). Prefer constructor injection.
What they are checking: Fundamental ASP.NET Core knowledge
Q10FresherMost askedFree with sign-inAnswerHideWhat is middleware in ASP.NET Core and why does the order matter?
Middleware are components in the request pipeline. Each receives the request, can act before and after calling the next component, or short-circuit the pipeline.
Q11FresherMost askedFree with sign-inAnswerHideExplain the MVC pattern in ASP.NET Core. How is it different from Web API?
MVC splits an application into three parts. The Model holds data and business rules. The View makes the HTML with Razor. The Controller handles requests, calls the model and chooses a view.
Q12FresherMost askedFree with sign-inAnswerHideWhat is Entity Framework Core? What is change tracking and when would you use AsNoTracking?
EF Core is an ORM (a tool that maps C# classes to database tables). It turns LINQ into SQL and tracks changes so it can save them.
Q13FresherMost askedFree with sign-inAnswerHideHow does garbage collection work in .NET? What are generations and the LOH?
The .NET GC automatically frees managed memory for objects that are no longer reachable from roots. It is generational, based on most objects dying young.
Q14FresherMost askedFree with sign-inAnswerHideWhat is IDisposable and the using statement? How do you implement the dispose pattern?
IDisposable is the contract for freeing unmanaged resources (file handles, sockets, DB connections) at a known time. using guarantees Dispose() runs even if an exception occurs.
Q15FresherMost askedFree with sign-inAnswerHideWhat is the difference between inner join, left join and right join in SQL Server? Write a query joining Orders and Customers.
- INNER JOIN: rows with matches in both tables.
- LEFT JOIN: all rows from the left table, matched rows from the right, NULL where no match.
- RIGHT JOIN: the mirror image.
- FULL OUTER JOIN: all rows from both.
Q16FresherMost askedFree with sign-inAnswerHideWrite a SQL query to find the second highest salary, and the top earner per department.
Use window functions for flexibility. DENSE_RANK handles ties correctly.
Q17FresherMost askedFree with sign-inAnswerHideWrite C# to find duplicate elements in a list and the first non-repeating character in a string.
LINQ with grouping, or a dictionary for counts, solves both in O(n).
Q18FresherMost askedFree with sign-inAnswerHideExplain virtual, override, new and sealed in C#.
virtual allows a method to be overridden. override replaces it in a child class. new hides it. sealed stops any more overriding.
Q19FresherMost askedFree with sign-inAnswerHideWhat are delegates and events in C#? What is the difference?
A delegate is a type-safe reference to a method. An event is a limited delegate field that lets a class publish notifications. Outside code can only subscribe or unsubscribe. It cannot call the event or overwrite it.
Q20FresherMost askedFree with sign-inAnswerHideWhat are generics in C# and why use them? What are generic constraints?
Generics let you write type-safe code parameterised by type, with no casting and no boxing for value types.
Q21FresherMost askedFree with sign-inAnswerHideHow do EF Core migrations work? How do you apply them safely in production?
A migration is a generated C# class that records a schema change (Up and Down). EF compares your model with the last snapshot to create it, and stores applied migrations in the __EFMigrationsHistory table.
Q22FresherMost askedFree with sign-inAnswerHideWhat is the difference between const, readonly and static readonly?
const is a compile-time constant. readonly is assigned at runtime once, in a declaration or constructor.
Q23FresherMost askedFree with sign-inAnswerHideWhat is the difference between .NET Framework, .NET Core and .NET 8?
They are generations of Microsoft's platform.
Q24FresherMost askedFree with sign-inAnswerHideWhat is the difference between IEnumerable, ICollection, IList and List<T>?
They form a hierarchy of increasing capability.
IEnumerable<T>: forward-only iteration (foreach). Possibly lazy.ICollection<T>: addsCount,Add,Remove,Contains.IList<T>: adds index access and insert at a position.List<T>: the concrete resizable array implementing all of them.
Q25FresherMost askedFree with sign-inAnswerHideWhat is the difference between string and StringBuilder in C#? What is string interpolation?
string is immutable, so each concatenation creates a new string. StringBuilder is a mutable buffer for repeated modification.
Q26FresherMost askedFree with sign-inAnswerHideWrite a C# program to check whether a string is a palindrome, ignoring case and non-alphanumeric characters.
Use two pointers, skipping characters that are not letters or digits. This is O(n) time and O(1) extra space.
Q27FresherMost askedFree with sign-inAnswerHideWhat is the difference between ref, out and in parameters?
All pass by reference instead of by value, differing in initialisation and write rules.
C# and .NET interview questions for experienced 15
Q28ExperiencedMost askedAnswerHideWhat happens when you call .Result or .Wait() on a Task? What is the sync-over-async deadlock?
They block the calling thread until the task completes. In an environment with a synchronization context (classic ASP.NET, WinForms, WPF), this can deadlock.
The deadlock: the UI or request thread calls GetAsync().Result and blocks. Inside, the code after await tries to resume on that same saved context. But the thread is blocked waiting, so neither can move on.
// Risky in UI / legacy ASP.NET
var data = LoadAsync().Result;
// Fix: async all the way
var data2 = await LoadAsync();
// In library code: do not capture the context
await SomeCallAsync().ConfigureAwait(false);
ASP.NET Core has no synchronization context, so this exact deadlock does not happen there. But blocking still wastes pool threads and can leave no free threads under load. Rule: go async all the way, avoid .Result, .Wait() and GetAwaiter().GetResult(), and use ConfigureAwait(false) in general-purpose libraries.
What they are checking: A favourite senior question: whether you know the cause, not just the slogan
Q29ExperiencedMost askedFree with sign-inAnswerHideWhat is the N+1 query problem in EF Core and how do you fix it?
N+1 means one query loads N parents, then one extra query per parent loads related data, giving N+1 round trips.
Q30ExperiencedMost askedFree with sign-inAnswerHideWhat is the difference between clustered and non-clustered indexes in SQL Server, and how do you find out why a query is slow?
A clustered index sets the physical order of the table rows. So a table has only one (the primary key by default). A non-clustered index is a separate structure. It holds the key columns plus a pointer (the clustering key) to the row. A table can have many.
Q31ExperiencedMost askedFree with sign-inAnswerHideHow do you use AI coding assistants (Copilot, Cursor, Claude Code) in daily .NET work? How do you make sure the output is reliable?
Use them as a fast pair programmer, and keep ownership of design and verification.
Q32ExperiencedMost askedFree with sign-inAnswerHideWhat is the difference between Task and Thread? What is the difference between Task.Run and async/await?
A Thread is an OS thread you manage yourself. A Task is a higher-level unit of work scheduled on the thread pool. It may not even use a thread while it waits for I/O.
Q33ExperiencedMost askedFree with sign-inAnswerHideWhy should you avoid async void? And how do you run several async operations in parallel?
async void cannot be awaited, and exceptions thrown in it cannot be caught by the caller. They are raised on the synchronization context and can crash the process. Use it only for event handlers.
Q34ExperiencedMost askedFree with sign-inAnswerHideHow do you handle errors globally in an ASP.NET Core Web API?
Use the exception handling middleware, and in .NET 8 an IExceptionHandler that returns RFC 7807 ProblemDetails.
Q35ExperiencedMost askedFree with sign-inAnswerHideHow does authentication with JWT work in ASP.NET Core?
The client logs in, the server issues a signed JWT, and the client sends it as Authorization: Bearer <token> on later requests. The JWT bearer middleware validates the signature, issuer, audience and expiry, and builds the ClaimsPrincipal.
Q36ExperiencedMost askedFree with sign-inAnswerHideHow do you use IHttpClientFactory and why not create a new HttpClient each time?
Creating a new HttpClient() per request can exhaust sockets (ports stay in TIME_WAIT), while a single static client never refreshes DNS. IHttpClientFactory pools and recycles the underlying handlers and gives you named or typed clients with policies.
Q37ExperiencedMost askedFree with sign-inAnswerHideExplain agentic workflows, sub-agents, spec-driven development and MCP in the context of AI-assisted coding.
These are patterns for letting AI tools do larger, more reliable pieces of work.
Q38ExperiencedMost askedFree with sign-inAnswerHideHow do you handle concurrency and transactions in EF Core?
SaveChanges runs inside one transaction by default. For multi-step work, use a transaction that you start yourself. For concurrent edits use optimistic concurrency.
Q39ExperiencedMost askedFree with sign-inAnswerHideHow would you implement pagination in SQL Server and in EF Core?
Use OFFSET ... FETCH with a deterministic ORDER BY. For deep pages or feeds use keyset pagination.
Q40ExperiencedMost askedFree with sign-inAnswerHideWhat are records, init-only properties and primary constructors in modern C#?
Modern C# adds concise ways to model data.
Q41ExperiencedMost askedFree with sign-inAnswerHideWrite a thread-safe producer-consumer example in C#.
Use System.Threading.Channels, the modern async-friendly bounded queue, instead of manual locks.
Q42ExperiencedMost askedFree with sign-inAnswerHideWhat is the difference between Minimal APIs and controllers in ASP.NET Core?
Both build HTTP endpoints on the same pipeline. Minimal APIs are lightweight and function based, while controllers are class based with more built-in conventions.
Scenario based C# and .NET interview questions 8
Q43ExperiencedMost askedScenarioFree with sign-inAnswerHideAn ASP.NET Core API is slow under load. How do you diagnose and fix it?
Measure first, find the bottleneck layer, then fix and verify.
Q44ExperiencedMost askedScenarioFree with sign-inAnswerHideA singleton service depends on a scoped service, such as a DbContext. What goes wrong and how do you fix it?
This is the captive dependency problem. The singleton holds the first scoped instance forever, so a DbContext is shared across requests and threads. It is not thread safe, it caches tracked entities (stale data) and grows without bound.
Q45ExperiencedMost askedScenarioFree with sign-inAnswerHideWhat is wrong with this code? for (int i = 0; i < 3; i++) tasks.Add(Task.Run(() => Console.WriteLine(i)));
Many closures read the loop variable after the loop has advanced, so you may see repeated or unexpected values.
Q46ExperiencedMost askedScenarioFree with sign-inAnswerHideYour .NET service's memory grows until the container is killed. How do you find the leak?
Find what is kept in memory, using dumps and counters. Then fix the root cause.
Q47ExperiencedMost askedScenarioFree with sign-inAnswerHideAfter a release, an endpoint returns HTTP 500 intermittently for a few users only. How do you troubleshoot it?
Treat it as an evidence hunt: narrow what the failing requests have in common.
Q48ExperiencedMost askedScenarioFree with sign-inAnswerHideHow would you stop duplicate order submissions when a user double-clicks or a client retries a POST request?
Make the operation idempotent on the server, and do not rely only on disabling the button.
Q49ExperiencedMost askedScenarioFree with sign-inAnswerHideHow do you run background jobs in ASP.NET Core?
Use a hosted service for in-process work, and a durable job system when jobs must survive restarts.
Q50ExperiencedMost askedScenarioFree with sign-inAnswerHideHow would you migrate a legacy .NET Framework application to .NET 8?
Migrate incrementally and keep the system running, rather than a risky big-bang rewrite.