Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close

    Interview questions

    C# and .NET interview questions

    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.

    Full answer

    2. What is object casting and pattern matching?

    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.

    Full answer

    3. What is boxing and unboxing?

    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.

    Full answer

    4. Value type vs reference type?

    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.

    Full answer

    5. Do value types inherit from object?

    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.

    Full answer

    6. Class vs struct: when should each be used?

    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.

    Full answer

    7. Are nullable types reference types?

    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.

    Full answer

    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.

    Full answer

    9. Why are strings immutable in C#?

    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.

    Full answer

    10. string vs StringBuilder?

    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.

    Full answer

    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.

    Full answer

    12. Is string.Empty faster than ""?

    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.

    Full answer

    13. What is a verbatim string literal?

    A verbatim string keeps backslashes and line breaks as written. I double any quote that belongs inside the text.

    Full answer

    14. What are raw string literals?

    A raw string uses three or more matching double quotes. It helps me embed text like JSON without adding ordinary C# escapes to each quote.

    Full answer

    15. const, readonly, and static readonly?

    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.

    Full answer

    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.

    Full answer

    17. What are default access modifiers in C#?

    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.

    Full answer

    18. Why do we need namespaces?

    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.

    Full answer

    19. var vs dynamic?

    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.

    Full answer

    20. What are numeric literal suffixes?

    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.

    Full answer

    21. decimal vs double vs float?

    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.

    Full answer

    22. What is banker rounding?

    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.

    Full answer

    23. What is nameof used for?

    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.

    Full answer

    24. What are expression-bodied members?

    I use an expression body when a single expression describes the member clearly. For a method returning a value, it replaces the braces and return.

    Full answer

    25. What is a tuple / ValueTuple?

    A tuple groups a few values for a local result. When the result needs lasting meaning and rules of its own, I prefer a named type.

    Full answer

    26. What is an indexer?

    An indexer lets callers read or write through brackets. The type decides what the key means and which operations it supports.

    Full answer

    27. What is operator overloading?

    An overload defines an operator for my type. I use it only when its meaning is natural to callers.

    Full answer

    28. Why can some operators not be applied to generic types?

    An unconstrained T does not guarantee addition. I add the narrowest constraint that promises the operator the method needs.

    Full answer

    29. What causes OutOfMemoryException?

    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.

    Full answer

    30. What is the stack and heap in .NET?

    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.

    Full answer

    From the lesson Core C# and CLR basics

    Common C# and .NET misconceptions

    31. Do value types always live on the stack?

    "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."

    Full answer

    32. Does async create a new thread?

    "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."

    Full answer

    33. Is IQueryable just a faster IEnumerable?

    "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."

    Full answer

    34. Does new List<T>(10) hold ten items?

    "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."

    Full answer

    35. Is a hash code unique?

    "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."

    Full answer

    36. Can you change a list inside foreach?

    "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."

    Full answer

    37. Does the garbage collector call Dispose?

    "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."

    Full answer

    From the lesson Common misconceptions, corrected

    Modern C# features

    38. What are collection expressions in C#?

    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.

    Full answer

    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.

    Full answer

    40. What is target-typed new?

    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.

    Full answer

    41. What is a with-expression?

    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.

    Full answer

    42. What are extension blocks in C# 14?

    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.

    Full answer

    43. What is the C# field keyword in properties?

    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.

    Full answer

    44. What is a file-local type?

    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.

    Full answer

    45. What are partial classes and partial methods?

    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.

    Full answer

    46. What is explicit interface implementation?

    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.

    Full answer

    47. What is using static?

    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.

    Full answer

    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.

    Full answer

    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.

    Full answer

    50. What is generic math in .NET?

    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.

    Full answer

    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.

    Full answer

    52. What does scoped mean in ref-safe code?

    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.

    Full answer

    53. What are readonly members in structs?

    readonly instance members (C# 8) promise not to mutate the struct instance. They can reduce defensive copies and communicate immutability intent for value types.

    Full answer

    From the lesson Modern C# language features

    Equality, copying and nullability

    54. What is IEquatable<T> and why is it useful?

    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.

    Full answer

    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.

    Full answer

    56. What is shallow copy vs deep copy?

    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.

    Full answer

    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.

    Full answer

    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.

    Full answer

    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.

    Full answer

    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.

    Full answer

    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.

    Full answer

    62. What rules must Equals follow?

    “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.”

    Full answer

    63. Why must GetHashCode agree with Equals?

    “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.”

    Full answer

    64. How do you implement an immutable Money class?

    “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.”

    Full answer

    65. Can unequal values have the same hash code?

    “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.”

    Full answer

    66. How can inheritance break equality symmetry?

    “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.”

    Full answer

    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.”

    Full answer

    From the lessons Equality, copying, nullability, and safe APIs and Equality and Hash-Code Contracts for Immutable C# Value Keys

    LINQ and performance

    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.”

    Full answer

    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.”

    Full answer

    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.”

    Full answer

    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.”

    Full answer

    72. Why is List<T>.Add O(1) amortized?

    “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.”

    Full answer

    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.”

    Full answer

    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.”

    Full answer

    75. What is deferred execution in LINQ?

    “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.”

    Full answer

    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.”

    Full answer

    77. Is deferred execution the same as streaming?

    “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.”

    Full answer

    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.”

    Full answer

    79. Will a deferred LINQ query see source changes?

    “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.”

    Full answer

    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.”

    Full answer

    From the lessons Big-O for .NET Developers: Time and Space in LINQ and Deferred Execution and Multiple Enumeration: Paying for the Same Query Twice

    ASP.NET Core

    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.”

    Full answer

    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.”

    Full answer

    83. What do Build, Run and StartAsync do?

    “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.”

    Full answer

    84. Do hosted services start before Kestrel?

    “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.”

    Full answer

    85. How does Kestrel pass requests to the app?

    “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.”

    Full answer

    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.”

    Full answer

    87. What happens during graceful shutdown?

    “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.”

    Full answer

    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.”

    Full answer

    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.”

    Full answer

    90. Does code after await next always run?

    “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.”

    Full answer

    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.”

    Full answer

    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.”

    Full answer

    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.”

    Full answer

    94. How do you write custom middleware?

    “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.”

    Full answer

    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.”

    Full answer

    96. How does ASP.NET Core build a ClaimsPrincipal?

    “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.”

    Full answer

    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.”

    Full answer

    98. When should an API return 401 or 403?

    “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.”

    Full answer

    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.”

    Full answer

    100. How do you check ownership and tenant access?

    “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.”

    Full answer

    From the lessons How an ASP.NET Core App Starts: WebApplication, the Generic Host and Kestrel, The Request Pipeline: Middleware Order, Short-Circuits and Branches and Authentication, Authorization and Trust Boundaries

    EF Core

    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.”

    Full answer

    102. When does an EF Core query hit the database?

    “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.”

    Full answer

    103. What changes after AsEnumerable or ToList?

    “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.”

    Full answer

    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.”

    Full answer

    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.”

    Full answer

    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.”

    Full answer

    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.”

    Full answer

    108. What are the five entity states in EF Core?

    “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.”

    Full answer

    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.”

    Full answer

    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.”

    Full answer

    111. Does EF Core update every column?

    “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.”

    Full answer

    112. What does SaveChanges actually do?

    “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.”

    Full answer

    113. Does a tracking query return fresh values?

    “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.”

    Full answer

    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.”

    Full answer

    From the lessons How EF Core Runs a Query: Expression Trees, SQL, Logging and ToQueryString and Change Tracking: Entity States, Snapshots, DetectChanges and the Identity Map