114 questions that come up in C# and .NET developer interviews. Each has a short answer you can say aloud, and a link to its full answer.
Updated 1 Dec 2026
C# basics: types, strings and memory
1.What is the difference between casting, conversion, and parsing?
A conversion lets me use a value as another type. A cast requests one explicitly with (TargetType)value. Parsing reads text and returns a typed value. For uncertain input, I use TryParse and check whether it succeeded.
A reference cast uses the same object through another compatible reference type. It does not change the object. I use a type pattern to check an uncertain type before using it. An incompatible non-null reference cast throws InvalidCastException.
Boxing an int puts a copy of its value into an object. I unbox it as int first, then perform a separate numeric conversion if I need a long. Changing the original variable does not change its boxed copy.
Ordinary assignment copies a value or an object reference. Copying a reference can leave two variables pointing to one object. Changing that object affects what both see. Reassigning one variable does not reassign the other. A struct copy can still share objects through its reference-type fields.
Yes. Structs inherit from object through ValueType, and enums through Enum and ValueType. That type relationship does not make every integer a separate object. Converting an int to object boxes a copy. Converting a reference-type value to object does not box it.
I use a class when callers should share one object or when I need class inheritance. I consider a small struct when independent copies should represent independent values. I usually design it so its data cannot change after it is created. I choose by behavior first, then measure performance where it matters.
No. Int question mark is a value type that can also represent no value. String question mark is still string. Its annotation helps the compiler check for possible null use. It does not create a new type or prevent null at runtime.
8.What is the difference between object and System.Object, string and System.String?
Object and System.Object name the same type, just as string and System.String do. The short forms are C# aliases. Choosing one spelling changes readability, not the type or its performance.
Strings are immutable, which makes their text safe to share and useful as stable dictionary keys. String operations leave the original unchanged and return a result. I can assign that result to a variable, but that does not edit the old string.
I use strings for ordinary text. I consider StringBuilder when I repeatedly append or edit many pieces, because it can avoid repeatedly copying the whole growing string. I call ToString when I need the result and measure before claiming it is faster for my workload.
11.How should case-insensitive string comparison be done?
I choose the comparison based on what the text means, and I use the same rule for lookup. If a system defines READY and ready as the same status code, I use OrdinalIgnoreCase to compare them.
There is no meaningful speed difference in ordinary code. Both spellings mean a string with zero characters. For a form, I choose whether missing text means only empty, also null, or also whitespace.
Const is known at compile time. Instance readonly is set as an object is constructed. Static readonly belongs to the type and may be initialized at runtime.
16.Static field initializer vs static constructor?
A static field initializer is good for a simple starting value. A static constructor can run several initialization steps and also changes the runtime’s freedom to choose when they occur.
A class or struct declared directly in a namespace defaults to internal. Members I declare inside a class or struct default to private. Interface members default to public, and enum members are always public. A compiler-generated class constructor follows its own rule: public normally, protected for an abstract class.
Namespaces group related types and let different parts of a program use the same short type name without a clash. An assembly is a compiled unit. It is a separate concept.
Var lets the compiler infer a fixed local-variable type and keeps normal type checking. Dynamic delays checks for operations such as method calls until runtime, so a call can compile and still fail when executed.
A suffix specifies a numeric literal's type. With var, that type also becomes the variable's type. For example, 12.50m is decimal, while 12.50 and 12.50D are both double.
Float and double store binary approximations, with double offering more precision and range. Decimal can represent common decimal amounts exactly, but it also has limits. I choose the type for the data and define the rounding or comparison rules separately.
Banker's rounding chooses the result with an even last kept digit at an exact midpoint. Math.Round uses this ToEven rule unless I supply another mode. A value that is not a midpoint is rounded to the nearer result.
Nameof gives me the name of a variable, type or member as a string at compile time. It does not read its value, and it helps named error messages keep up with code renames.
An allocation can fail because of limits or available address space even when system RAM is not exhausted. I first check what my process retains and what it is trying to allocate.
The stack supports active calls on a thread. The managed heap holds objects tracked by the garbage collector. Value versus reference describes copying behavior, not a promise about physical storage.
"A value type is copied by value. Where its data is stored depends on where the variable is. A struct that is an instance field of a class is stored inside the object, so it lives wherever that object lives. Value type does not mean stack."
"await does not start a thread and does not block the calling thread. If the task is already complete, the method continues at once, with the task's result or its exception. If it is not, the method is suspended and its caller gets control back; when the task completes, the rest of the method continues. Whether a thread works in the meantime depends on the operation: waiting for a network answer usually needs none, and heavy calculation started with Task.Run uses a thread-pool thread."
"With IEnumerable<T>, LINQ runs my lambdas as compiled code inside my program. IQueryable<T> keeps the query as an expression tree, and a provider such as EF Core translates what it supports, for example to SQL. Where the query runs depends on the provider and on the point where I load the results, for example with ToList."
"Capacity is the size of the list's internal array, so it is the number of items the list can hold before it has to grow. Count is the number of items that are in the list now. new List<T>(10) gives Count 0 and Capacity 10."
"No. A hash code is an int, so different values can share one. That is a collision. The rule is that equal values must return the same hash code. The reverse is not guaranteed: equal hash codes do not prove that two values are equal. A dictionary uses the hash code to find the bucket and Equals to confirm the match."
"foreach does not make a collection read-only. For List<T>, adding, removing or replacing an element while the loop runs invalidates the enumerator, and its next MoveNext throws InvalidOperationException. Other collections have their own rules."
"The GC reclaims managed memory, the memory that .NET looks after. It does not call Dispose. I release the resources my code owns, such as the files and connections it opened, promptly with using, or with await using when the disposal is asynchronous. A finalizer is only a safety net that may run later. It does not replace Dispose."
Collection expressions (C# 12) use square brackets to create arrays, spans, lists, and other collection-like targets with one compact syntax. They are not LINQ queries; the elements are evaluated and a concrete collection is created for the target type.
39.What is the spread element in a collection expression?
The spread element copies items from another collection into the new collection expression. It is useful for combining small sequences without manual AddRange calls.
Target-typed new (C# 9) lets the compiler infer the type from the left side or parameter type. It reduces repetition, but overuse can make code less readable when the target type is far away.
A with-expression copies a record class (C# 9), struct/record struct, or anonymous type (C# 10), then assigns selected accessible members on the copy. It is commonly used for immutable models and request/response DTOs.
Extension blocks (C# 14) are syntax for grouping extension members for a type. They can define extension methods, extension properties, and static extension members. The older this-parameter extension method syntax still works.
The field contextual keyword (C# 14) lets a property accessor refer to the compiler-generated backing field without manually declaring a private field. It is useful for validation in auto-property-like code.
A file-local type (C# 11) is visible only inside the source file where it is declared. It is useful for source generators or helper types that should not leak into the rest of the assembly.
partial lets a type or member be split across files and combined at compile time. It is common in generated code, UI designer code, and source-generator scenarios.
Explicit interface implementation implements an interface member so it is accessible only through the interface reference. It avoids public API pollution and resolves member-name conflicts.
using static imports static members of a type so they can be called without qualifying the type name. It is common for Math, assertion APIs, or test helper methods.
48.What are CallerMemberName and CallerArgumentExpression used for?
Caller info attributes substitute source information into omitted optional arguments at compile time, without stack inspection. CallerMemberName arrived in C# 5; CallerArgumentExpression in C# 10 (.NET 6). CallerMemberName is useful for logging and property change notification. CallerArgumentExpression is useful for guard clauses that report the failed expression.
49.What are static abstract members in interfaces?
Static abstract interface members (C# 11) let an interface require static members such as operators or factory methods. They enable generic algorithms over numeric-like types.
Generic math (.NET 7 with C# 11) lets you write numeric algorithms once and use them for int, decimal, double, and custom numeric types that implement the required numeric interfaces.
51.What do unmanaged, notnull, and default generic constraints mean?
unmanaged (C# 7.3) restricts T to non-nullable value types with no managed references in their fields. notnull (C# 8) requests non-nullable type arguments; violations produce warnings in a nullable-enabled context, not a runtime null check. default (C# 9) disambiguates an override or explicit interface implementation whose inherited type parameter has neither a class nor a struct constraint. It is not a general-purpose constraint for new generic methods.
scoped (C# 11) restricts escape of a ref-like value or reference. A scoped ReadOnlySpan<char> parameter can be consumed in the method but cannot be returned as a span derived from that parameter; scoped ref T instead restricts escape of the reference. These are compile-time lifetime rules, not allocation or ownership instructions.
readonly instance members (C# 8) promise not to mutate the struct instance. They can reduce defensive copies and communicate immutability intent for value types.
IEquatable<T> defines strongly typed Equals(T). Generic equality infrastructure such as EqualityComparer<T>.Default can use it, so struct comparisons can avoid the boxing required by an object-based call. It is not a promise that every use avoids boxing: assigning a struct to an interface or passing it as object can still box it. It defines equality, not ordering.
55.ReferenceEquals vs Equals: what is the difference?
object.ReferenceEquals(a, b) tests identity: the same object instance, or both references null. It cannot be overridden. Equals tests the equality defined by the selected method: ordinary classes inherit reference equality unless they override it, while strings and records provide value-based equality. object.Equals(a, b) is null-safe; calling a.Equals(b) throws if a is null.
A reference tells the program which object to use. A shallow copy creates a new outer object and copies its stored values, including any references to other objects. Those nested objects remain shared.
57.What are checked and unchecked numeric contexts?
For built-in integral arithmetic such as addition, checked reports overflow with OverflowException; unchecked discards excess bits, producing wraparound. Overflow in a constant expression is a compile-time error by default, unless explicitly unchecked. Nonconstant expressions default to unchecked unless the compiler's CheckForOverflowUnderflow option changes that default.
58.What are nullable analysis attributes such as MemberNotNull?
These attributes describe null-state contracts to the compiler. MemberNotNull promises that named members are non-null when the annotated method returns normally, not that the attribute itself initializes them. NotNullWhen(true) describes a parameter's state after a successful Boolean result; NotNullIfNotNull relates an output's state to an input's. Nullable analysis requires a nullable-enabled context (C# 8+); MemberNotNull support arrived with C# 9/.NET 5.
59.What is the difference between a guard clause and validation?
A guard clause is an early-exit control-flow pattern; validation is checking whether data satisfies rules. They overlap, rather than being opposites. API guards often throw standard argument exceptions for violated preconditions. Expected invalid user input is usually better represented as validation errors that a caller can display or map to a response.
60.What are discriminated unions, and how do developers approximate them in C#?
A discriminated union represents exactly one of a defined set of cases, each potentially carrying different data. In C# 14 and earlier, developers approximate this with records and inheritance, dedicated result types, or libraries. Unlike a closed union, an ordinary public class hierarchy does not give the compiler a complete set of possible subclasses for exhaustive matching.
61.What is a Result type and when is it better than exceptions?
A Result type makes expected success or failure explicit in a method's return value. It is useful for outcomes such as a declined payment or rejected input that callers routinely handle. Exceptions still suit contract violations and failures the method cannot usefully handle. This is an API design choice, not a rule that every predictable failure must stop using exceptions; .NET also uses patterns such as TryParse.
“Equals must be reflexive, symmetric, transitive, and consistent while the compared state is unchanged. A non-null object's Equals(null) returns false, and equality checks should not throw.”
“Equal values must have equal hashes. Hash collections narrow candidates by hash before checking Equals, so inconsistent hashes can cause missed lookups or duplicate logical values. I normally combine the equality fields with HashCode.Combine.”
“Overloaded == and != should agree with Equals and handle null safely. For Money, I use immutable data, typed IEquatable<Money> equality, and matching object equality and hashing. EqualityComparer<T>.Default uses IEquatable<T> when available.”
“Yes, unequal objects can have the same hash code; that is a collision. Equals still decides whether they match. Collisions cost lookup time, not correctness, when the equality and hash contracts hold.”
“If a base class's Equals uses an 'is' type check, it can accept a derived object whose Equals rejects the base object, breaking symmetry. For a value class I usually seal it. Otherwise, I need a consistent exact-runtime-type policy across the hierarchy.”
67.Why are immutable keys reliable, and can a record replace Money?
“Immutable keys keep equality-relevant state fixed, which keeps equality and hashing stable while stored. Immutability cannot fix a bad implementation, mutable internals, or a changing comparer. For simple Money data, a readonly record struct can generate the equality members.”
68.How do you choose the input size and cost model?
“I first define the input sizes and the operations I am counting. I then calculate how that work grows. I give separate answers for time and extra storage rather than predicting milliseconds.”
69.What do O(1), O(log n), O(n), O(n log n), and O(n²) mean?
“Constant work stays bounded. Logarithmic work grows through repeated reductions, linear work follows the input size, linearithmic work follows n times log n, and quadratic work follows n squared. These describe scaling, not exact speed.”
70.How do consecutive loops and nested loops combine?
“I add consecutive costs and multiply full nested scans. Two scans of n are O(n). Scanning m items for each of n items is O(n·m), becoming O(n²) when both sizes are n.”
71.How do time complexity and extra-space complexity differ in LINQ?
“Both examples scan n values, but their storage differs. A running total uses O(1) extra space; collecting up to n matches uses O(n). I state whether I include output storage.”
“Best and worst cases describe the cheapest and most expensive inputs of a given size. Average case uses an assumed mix of inputs. Amortized cost averages work across a sequence of operations, with no probability assumption. List.Add is O(1) within capacity and O(n) when resizing. Geometric growth makes it O(1) amortized per addition.”
73.How do helper collections change the total complexity?
“With suitable hashing and constant-cost equality, building the set and probing it gives expected O(m + n) time and O(m) extra space. I include construction, and I do not claim hashing guarantees constant-time lookups in the worst case.”
74.Can two O(n) LINQ queries have different performance?
“Two O(n) algorithms can have different constants, per-element work, allocations, and runtime optimizations. Big-O compares growth. I measure representative inputs to compare actual running time.”
“Deferred execution delays work until results are consumed. Operators returning IEnumerable<T> are usually deferred. Immediate operators such as Count, First, Sum, ToList and ToArray execute when called. Standard Where and Select queries do not cache results, so another enumeration can repeat the work.”
76.Does Any followed by Count enumerate a query twice?
“Any and Count are separate consumption points. On a filtered sequence, Any can stop at the first match, while Count must establish the full count. Multiple enumeration can repeat filtering, computation, I/O or side effects, but it is not always two full scans.”
“Deferred and streaming are different. Deferred means execution starts later. Streaming means results can arrive incrementally. Where can stream, while enumerating ordered output from OrderBy normally requires buffering the source before returning the first result.”
78.How can you avoid multiple enumeration of an expensive query?
“For expensive results that must be reused, I materialize a bounded query once with ToList or ToArray. That retains O(r) results, and later traversals still cost time. If I only need several summaries, I compute them in one pass without storing every result.”
“A deferred query reads the source when enumerated, so changes before another pass can affect the results. ToList saves the elements produced by one pass. For class instances, it keeps references to the same objects rather than copying those objects.”
80.Can any IEnumerable be safely enumerated again?
“No, IEnumerable<T> does not guarantee repeatable enumeration. A source may repeat external work, return different data, or fail on another pass. I check whether the source supports another read and whether any file, connection or reader it needs is still open. I enable CA1851 to help find repeated consumption.”
81.How do WebApplication, the Generic Host and Kestrel fit together?
“The Generic Host owns services and application lifetime. WebApplication combines host control with request-pipeline and endpoint configuration. Kestrel is the default cross-platform HTTP server, not the host or the application.”
82.What does WebApplication.CreateBuilder configure by default?
“CreateBuilder configures settings sources, logging providers, dependency injection, host lifetime and web-server defaults, including Kestrel. Development adds user secrets, service-provider validation and the developer exception page.”
“CreateBuilder prepares defaults and services. Build creates the app and service provider. Run blocks until shutdown; RunAsync awaits that lifetime. I can configure Kestrel addresses through ASPNETCORE_URLS, --urls, launchSettings.json for local development, Kestrel:Endpoints, app.Urls or ListenAnyIP. Without address configuration, Kestrel uses http://localhost:5000.”
“By default, hosted services registered through builder.Services start sequentially before the web host service starts Kestrel. A slow StartAsync delays listening. Concurrent startup or custom registration can change completion order.”
“Kestrel can run without IIS. With IIS, in-process hosting is the default since ASP.NET Core 3.0. The app runs inside w3wp.exe using IISHttpServer and avoids an extra forwarding step. Out-of-process hosting uses the ASP.NET Core Module to forward requests to Kestrel in a separate process.”
86.Does ApplicationStarted mean the application is ready?
“ApplicationStarted means host startup completed, not that arbitrary background initialization finished. Kestrel may accept requests before the notification. If traffic depends on something like a warming cache, I use an explicit readiness condition.”
“The host signals ApplicationStopping. With default ordering, Kestrel drains before earlier hosted services stop in reverse order, then ApplicationStopped fires. ShutdownTimeout defaults to 30 seconds and requests cancellation; it does not kill the process.”
88.How does the ASP.NET Core middleware pipeline run?
“Middleware receives HttpContext and can call the next delegate or stop processing. Earlier middleware wraps later middleware. Requests enter in registration order, and normal returns resume in reverse order.”
89.What is the difference between Use, Run and short-circuiting?
“Use receives next and can continue or short-circuit. Run with a handler is terminal and has no next. Parameterless Run starts the host. A short-circuit skips downstream work, but normal upstream returns still happen, and it does not automatically create an error response.”
“After-next code runs on normal downstream completion, including a normal short-circuit. An exception propagating through the await skips it. I use try/finally for cleanup that must run on both normal completion and exception propagation.”
91.What is the difference between Map, MapWhen and UseWhen?
“Map branches by path segment and moves the prefix into PathBase. MapWhen branches by a predicate without rewriting the path. Both skip later main middleware on a match. UseWhen rejoins the main pipeline if its branch continues.”
92.Why does middleware order matter for routing and security?
“Earlier middleware wraps later middleware. Put exception handling early, routing before endpoint-aware CORS and authorization, CORS before authentication and authorization, and authentication before authorization. Early public static files bypass later checks. MapGet registers an endpoint, not an execution slot, and WebApplication can add middleware automatically.”
93.Can you change response headers after calling next?
“I can change headers after next only if the response has not started. HasStarted tells me whether headers are committed. For a header that should be set just before commitment, I register OnStarting before calling next.”
“For convention-based middleware, I take RequestDelegate in the constructor, write Invoke or InvokeAsync, and register it with UseMiddleware. The instance lives for the app, so scoped services go in InvokeAsync parameters. IMiddleware is the factory-based alternative, activated per request using its registered lifetime.”
95.What is the difference between authentication and authorization?
“Authentication establishes who is calling. Authorization decides whether that caller may perform this action on this resource. Successful authentication does not imply permission.”
“An authentication handler selected through a scheme validates credentials and builds a ClaimsPrincipal, normally exposed as HttpContext.User. Claims, including roles, are issuer statements. The API decides which validated statements satisfy its authorization rules.”
97.How do you stop new endpoints being public by accident?
“The fallback policy is null by default. I set it to require an authenticated user, mark intentional public endpoints AllowAnonymous, and test denied requests. Named and default policies stand on their own, and earlier static-file middleware is outside that protection.”
“An expired bearer token normally produces 401 with an invalid_token challenge when error details are enabled. Insufficient scope produces 403; ASP.NET Core does not add insufficient_scope by default. Cookie challenges can redirect, but .NET 10 recognized API endpoints return 401 or 403 by default. AllowCookieRedirect opts them back in.”
99.Where are the browser, identity provider, API and database trust boundaries?
“A signed JWT alone does not secure an API. I validate the token for this API, then enforce endpoint, ownership, and tenant authorization. Browser input remains untrusted, the database connection represents the API rather than the user's permission, and stolen bearer tokens can be replayed.”
“I use endpoint authorization for feature access and resource-based authorization for the requested object. I check ownership and tenant membership on the server before returning or changing data, using validated identity information rather than trusting request-supplied identifiers.”
101.How do DbContext, DbSet and expression trees fit together?
“A DbContext represents a database session, and a DbSet is a query starting point for an entity type. IQueryable preserves an expression tree that EF Core and its provider can translate into SQL.”
“EF Core uses deferred execution. Where and OrderBy build the query; enumeration or operators such as ToList, First, Count and Any execute it. Building a query still has a CPU and allocation cost. Reusing the query normally executes SQL again; reusing a list that ToList already filled with results does not.”
“For an EF Core query, IQueryable holds an expression tree that the provider translates into SQL for the database. After AsEnumerable, IEnumerable operators run in .NET as rows are read. AsEnumerable alone does not execute the query. ToList executes and stores the results. Moving filters into .NET can fetch unnecessary rows.”
104.What happens between a LINQ query and its results?
“EF processes the expression tree, extracts suitable values as parameters and checks its query cache. When needed, the provider translates it into SQL. EF executes the command and materializes results. Entity queries track by default and can reuse tracked instances, but the query cache does not cache rows.”
105.How do ToQueryString and command logging show SQL?
“Use ToQueryString during development to inspect SQL without execution. Use LogTo or the Database.Command category to see commands that actually ran. Tags help connect those commands to application code and database tools. I keep sensitive-data logging disabled in production.”
106.When should you use Find, FirstOrDefault or SingleOrDefault?
“Find checks the tracker for a primary key before querying. First and FirstOrDefault take one match. Single and SingleOrDefault reject multiple matches. First and Single throw when nothing matches; the OrDefault versions return default, which is null for entity results. I use Single when multiple matches should be an error.”
107.How do TagWith and TagWithCallSite identify a query?
“TagWith adds a recognizable SQL comment for correlating application queries with command logs and database tools. I use stable, non-sensitive labels because tags are literals, not parameters. TagWithCallSite adds the source-file location.”
“EF Core has five entity states. Detached means not tracked. Added means insert, Modified means update, and Deleted means delete when saved. Unchanged produces no write. Setting a state alone does not send SQL.”
109.How do snapshots and DetectChanges find edits?
“Default snapshot tracking compares current values with originals captured when tracking starts. SaveChanges, Entries and HasChanges normally trigger detection. If I disable automatic detection, I must explicitly detect ordinary property edits before saving.”
110.How can I inspect entity states and changed columns?
“I inspect Entry for one entity's state and property flags, or DebugView for the tracker as a whole. After ordinary edits, I run DetectChanges before reading DebugView so its states and modified flags are current.”
“Normal tracked edits update changed columns. Update, or setting the entity state to Modified, marks non-key properties as modified. Attach alone schedules no update for an existing entity. EF Core does not infer which request fields were supplied.”
“SaveChanges normally detects changes, orders and executes writes, uses a transaction when needed, and reads generated values. After successful default acceptance, Added and Modified become Unchanged, and Deleted becomes Detached. It returns state entries written, not SQL rows affected.”
“The identity map keeps one tracked instance per entity type and primary key. Another tracking query reuses it without refreshing its values. Reload deliberately refreshes it. Attaching another instance with the same key throws an InvalidOperationException saying another instance is already tracked. Reuse the tracked instance or copy the intended values onto it.”
114.Why does a growing change tracker cost more, and what does Clear do?
“A long-lived context accumulates tracked entities and snapshots, increasing memory use and detection work. Prefer short units of work. Clear stops tracking everything and drops pending tracked changes; it neither saves nor rolls back. It also does not make an unusable context safe.”