InterviewTreedInterviewTreed

InterviewTreed Question Bank

C# & .NET Development Interview Questions and Answers

Prepare for C# and .NET interviews, covering object-oriented programming, advanced C#, .NET internals, ASP.NET Core, Web APIs, Entity Framework Core, SQL integration, design patterns, testing, and application architecture.

Total Questions

150

Beginner

47

Intermediate

65

Advanced

38

Beginner Questions

Foundational concepts, terminology, and core ideas.

Q1Explain the .NET platform

What is .NET?

A developer platform from Microsoft for building web, desktop, cloud, mobile, and service applications. It includes runtimes, base libraries, SDKs, and lan

Answer

A developer platform from Microsoft for building web, desktop, cloud, mobile, and service applications. It includes runtimes, base libraries, SDKs, and language compilers.

Example: ASP.NET Core APIs, worker services, and console apps can all run on .NET.

Syntax

dotnet --info

Example

Example: ASP.NET Core APIs, worker services, and console apps can all run on .NET.

Code example

dotnet --info

Diagram

Explain the .NET platform → implementation → result

Key Points

  • Runtime executes managed code
  • libraries provide common functionality
  • SDK provides build and development tools.
Q2Compare modern .NET with .NET Framework

What is the difference between .NET and .NET Framework?

Modern .NET is cross-platform and actively developed for new applications. .NET Framework is Windows-only and mainly used for legacy applications that depe

Answer

Modern .NET is cross-platform and actively developed for new applications. .NET Framework is Windows-only and mainly used for legacy applications that depend on technologies such as Web Forms or older WCF server features.

Choose modern .NET for new development unless a required legacy dependency forces .NET Framework.

Syntax

dotnet --list-sdks

Example

Choose modern .NET for new development unless a required legacy dependency forces .NET Framework.

Code example

dotnet --list-sdks

Diagram

Compare modern .NET with .NET Framework → implementation → result

Key Points

  • Check library compatibility before migrating.
Q3Describe the Common Language Runtime

What is the CLR?

The CLR executes managed .NET code and provides services such as garbage collection, exception handling, type safety, and JIT compilation.

Answer

The CLR executes managed .NET code and provides services such as garbage collection, exception handling, type safety, and JIT compilation.

Example: a C# method is compiled to intermediate language and compiled to native code when needed.

Diagram / flow: C# source → CIL/IL → JIT machine code → CPU

Syntax

C# source → CIL/IL → JIT machine code → CPU

Example

Example: a C# method is compiled to intermediate language and compiled to native code when needed.

Code example

C# source → CIL/IL → JIT machine code → CPU

Diagram

Diagram / flow:
C# source → CIL/IL → JIT machine code → CPU

Key Points

  • CLR is the execution engine
  • CoreCLR is used by modern .NET.
Q4Explain Intermediate Language

What is CIL or IL?

C# compilers normally produce Common Intermediate Language (CIL), also called IL. The runtime then JIT-compiles IL to machine code for the target environme

Answer

C# compilers normally produce Common Intermediate Language (CIL), also called IL. The runtime then JIT-compiles IL to machine code for the target environment.

IL allows the same assembly to run on supported platforms with a compatible .NET runtime.

Diagram / flow: C# → compiler → IL assembly (.dll/.exe) → JIT → native code

Syntax

C# → compiler → IL assembly (.dll/.exe) → JIT → native code

Example

IL allows the same assembly to run on supported platforms with a compatible .NET runtime.

Code example

C# → compiler → IL assembly (.dll/.exe) → JIT → native code

Diagram

Diagram / flow:
C# → compiler → IL assembly (.dll/.exe) → JIT → native code

Key Points

  • IL is not the same as source code or native machine code.
Q5Compare .NET SDK and runtime

What is the difference between SDK and runtime?

The SDK contains tools to create, build, test, and publish applications. The runtime contains what is needed to execute a framework-dependent application.

Answer

The SDK contains tools to create, build, test, and publish applications. The runtime contains what is needed to execute a framework-dependent application.

A CI build agent generally needs the SDK; a deployment host may need only the appropriate runtime.

Syntax

dotnet --list-sdks
dotnet --list-runtimes

Example

A CI build agent generally needs the SDK; a deployment host may need only the appropriate runtime.

Code example

dotnet --list-sdks
dotnet --list-runtimes

Diagram

Compare .NET SDK and runtime → implementation → result

Key Points

  • Self-contained deployments bundle the runtime.
Q6Explain managed code

What is a managed application?

Managed code runs under the .NET runtime, which provides memory management and runtime services. C# applications are typically managed unless they delibera

Answer

Managed code runs under the .NET runtime, which provides memory management and runtime services. C# applications are typically managed unless they deliberately use unmanaged interop.

Example: the GC reclaims unreachable managed objects; it does not automatically manage every unmanaged resource.

Syntax

string message = "Hello .NET";

Example

Example: the GC reclaims unreachable managed objects; it does not automatically manage every unmanaged resource.

Code example

string message = "Hello .NET";

Diagram

Explain managed code → implementation → result

Key Points

  • Managed does not mean that bugs or resource leaks are impossible.
Q7Explain namespaces

What is a namespace in C#?

A namespace groups types and helps avoid naming collisions. The using directive lets code refer to types without repeating their full namespace.

Answer

A namespace groups types and helps avoid naming collisions. The using directive lets code refer to types without repeating their full namespace.

Use namespaces that reflect logical application boundaries.

Syntax

namespace InterviewTreed.Services;

public class EmailService { }

Example

Use namespaces that reflect logical application boundaries.

Code example

namespace InterviewTreed.Services;

public class EmailService { }

Diagram

Explain namespaces → implementation → result

Key Points

  • A namespace is not necessarily the same as a folder.
Q8Differentiate class and object

What is a class and an object?

A class defines state and behavior. An object is an instance of that class created at runtime.

Answer

A class defines state and behavior. An object is an instance of that class created at runtime.

The class is the blueprint; customer is one instance.

Syntax

public class Customer { public string Name { get; set; } = ""; }
var customer = new Customer { Name = "Asha" };

Example

The class is the blueprint; customer is one instance.

Code example

public class Customer { public string Name { get; set; } = ""; }
var customer = new Customer { Name = "Asha" };

Diagram

Differentiate class and object → implementation → result

Key Points

  • A class can have many instances.
Q9Compare value and reference types

What are value types and reference types?

Value types store their value directly in the variable or containing storage. Reference-type variables hold references to objects. Structs and enums are va

Answer

Value types store their value directly in the variable or containing storage. Reference-type variables hold references to objects. Structs and enums are value types; classes, arrays, and strings are reference types.

Copying a value type copies its value; copying a reference copies the reference, so both variables can refer to the same object.

Syntax

int count = 5;
Customer first = new Customer();

Example

Copying a value type copies its value; copying a reference copies the reference, so both variables can refer to the same object.

Code example

int count = 5;
Customer first = new Customer();

Diagram

Compare value and reference types → implementation → result

Key Points

  • Value/reference semantics are more precise than saying stack versus heap
  • actual storage depends on context.
Q10Explain nullable value types

What is the difference between int and nullable int?

An int cannot represent null. int? is shorthand for Nullable<int> and can represent either an integer or no value.

Answer

An int cannot represent null. int? is shorthand for Nullable<int> and can represent either an integer or no value.

Use nullable values when absence is meaningful, such as an optional database column.

Syntax

int? age = null;
int displayAge = age ?? 0;

Example

Use nullable values when absence is meaningful, such as an optional database column.

Code example

int? age = null;
int displayAge = age ?? 0;

Diagram

Explain nullable value types → implementation → result

Key Points

  • Nullable reference types are a separate compile-time feature.
Q11Explain properties and accessors

What are properties in C#?

Properties expose controlled access to state using get and set accessors. Auto-properties let the compiler generate backing storage.

Answer

Properties expose controlled access to state using get and set accessors. Auto-properties let the compiler generate backing storage.

Use private or init-only setters when callers should not freely change state.

Syntax

public string Name { get; set; } = "";
public int Age { get; private set; }

Example

Use private or init-only setters when callers should not freely change state.

Code example

public string Name { get; set; } = "";
public int Age { get; private set; }

Diagram

Explain properties and accessors → implementation → result

Key Points

  • A property is accessed like a field but can execute code.
Q12List C# access modifiers

What are access modifiers?

Access modifiers control where types and members can be accessed. Common modifiers are public, private, protected, internal, protected internal, private pr

Answer

Access modifiers control where types and members can be accessed. Common modifiers are public, private, protected, internal, protected internal, private protected, and file for top-level types in supported C# versions.

Prefer the least permissive accessibility that meets the design.

Syntax

public class A { private int _count; public int Count => _count; }

Example

Prefer the least permissive accessibility that meets the design.

Code example

public class A { private int _count; public int Count => _count; }

Diagram

List C# access modifiers → implementation → result

Key Points

  • internal generally means accessible within the same assembly.
Q13Explain constructors

What is a constructor?

A constructor initializes a new instance. It has the class name and no return type. C# also supports static constructors and primary constructors in suppor

Answer

A constructor initializes a new instance. It has the class name and no return type. C# also supports static constructors and primary constructors in supported versions.

Use constructors to establish required invariants.

Syntax

public class Product {
  public string Name { get; }
  public Product(string name) => Name = name;
}

Example

Use constructors to establish required invariants.

Code example

public class Product {
  public string Name { get; }
  public Product(string name) => Name = name;
}

Diagram

Explain constructors → implementation → result

Key Points

  • A constructor is not inherited.
Q14Explain overloading

What is method overloading?

Overloading defines multiple methods with the same name but different parameter signatures. Return type alone cannot distinguish overloads.

Answer

Overloading defines multiple methods with the same name but different parameter signatures. Return type alone cannot distinguish overloads.

The compiler selects an overload using argument types and overload-resolution rules.

Syntax

int Add(int a, int b) => a + b;
double Add(double a, double b) => a + b;

Example

The compiler selects an overload using argument types and overload-resolution rules.

Code example

int Add(int a, int b) => a + b;
double Add(double a, double b) => a + b;

Diagram

Explain overloading → implementation → result

Key Points

  • Changing only the return type does not create a valid overload.
Q15Compare parameter modifiers

What is the difference between ref, out, and in?

ref passes a variable by reference and requires it to be assigned before the call. out requires the method to assign it. in passes by readonly reference an

Answer

ref passes a variable by reference and requires it to be assigned before the call. out requires the method to assign it. in passes by readonly reference and is useful for some larger structs.

TryParse commonly uses out to return both success status and a parsed value.

Syntax

bool ok = int.TryParse("42", out int value);

Example

TryParse commonly uses out to return both success status and a parsed value.

Code example

bool ok = int.TryParse("42", out int value);

Diagram

Compare parameter modifiers → implementation → result

Key Points

  • These modifiers affect call semantics
  • they are not substitutes for returning a domain object.
Q16Explain enumerations

What is an enum?

An enum defines a set of named constants backed by an integral type. It makes code more readable than unexplained numeric values.

Answer

An enum defines a set of named constants backed by an integral type. It makes code more readable than unexplained numeric values.

Use enums for a closed set of values; validate external numeric input before casting.

Syntax

enum OrderStatus { Pending, Paid, Shipped, Cancelled }
OrderStatus status = OrderStatus.Paid;

Example

Use enums for a closed set of values; validate external numeric input before casting.

Code example

enum OrderStatus { Pending, Paid, Shipped, Cancelled }
OrderStatus status = OrderStatus.Paid;

Diagram

Explain enumerations → implementation → result

Key Points

  • Enum values default to zero unless explicitly assigned.
Q17Explain structs

What is a struct?

A struct is a value type, suitable for small values with value semantics. Structs can have methods and properties. Prefer immutable structs for predictable

Answer

A struct is a value type, suitable for small values with value semantics. Structs can have methods and properties. Prefer immutable structs for predictable behavior.

Point p = new(10, 20);

Syntax

public readonly record struct Point(int X, int Y);

Example

Point p = new(10, 20);

Code example

public readonly record struct Point(int X, int Y);

Diagram

Explain structs → implementation → result

Key Points

  • Avoid large mutable structs because copying them can be surprising or costly.
Q18Explain records

What is a record in C#?

Records are designed for data-centric types and provide value-based equality. Record classes are reference types; record structs are value types.

Answer

Records are designed for data-centric types and provide value-based equality. Record classes are reference types; record structs are value types.

The with expression creates a copy with selected properties changed.

Syntax

public record Person(string Name, int Age);
var p2 = p1 with { Age = 31 };

Example

The with expression creates a copy with selected properties changed.

Code example

public record Person(string Name, int Age);
var p2 = p1 with { Age = 31 };

Diagram

Explain records → implementation → result

Key Points

  • Value equality differs from the default reference equality of ordinary classes.
Q19Format strings with interpolation

What is string interpolation?

String interpolation embeds expressions inside a string using a dollar sign and braces.

Answer

String interpolation embeds expressions inside a string using a dollar sign and braces.

Use invariant formatting when a value must be culture-independent, such as machine-readable output.

Syntax

string name = "Mira";
string greeting = $"Hello, {name}!";

Example

Use invariant formatting when a value must be culture-independent, such as machine-readable output.

Code example

string name = "Mira";
string greeting = $"Hello, {name}!";

Diagram

Format strings with interpolation → implementation → result

Key Points

  • Interpolation improves readability but does not automatically sanitize SQL or HTML.
Q20Explain string immutability

Why are strings immutable?

A string cannot be changed after creation. Operations that appear to modify a string produce another string. Immutability simplifies sharing and hashing.

Answer

A string cannot be changed after creation. Operations that appear to modify a string produce another string. Immutability simplifies sharing and hashing.

Use StringBuilder for many incremental concatenations in loops when profiling shows it helps.

Syntax

string name = "Ada";
name += " Lovelace"; // creates a new string

Example

Use StringBuilder for many incremental concatenations in loops when profiling shows it helps.

Code example

string name = "Ada";
name += " Lovelace"; // creates a new string

Diagram

Explain string immutability → implementation → result

Key Points

  • Immutability does not mean strings are encrypted or safe for secrets.
Q21Explain arrays

What is an array?

An array stores a fixed-size sequence of elements of the same type and uses zero-based indexing.

Answer

An array stores a fixed-size sequence of elements of the same type and uses zero-based indexing.

Use List<T> when the collection size needs to change.

Syntax

int[] scores = { 80, 91, 76 };
int first = scores[0];

Example

Use List<T> when the collection size needs to change.

Code example

int[] scores = { 80, 91, 76 };
int first = scores[0];

Diagram

Explain arrays → implementation → result

Key Points

  • Accessing an invalid index throws IndexOutOfRangeException.
Q22Explain generic lists

What is List<T>?

List<T> is a resizable, strongly typed collection. It supports adding, removing, searching, and indexed access.

Answer

List<T> is a resizable, strongly typed collection. It supports adding, removing, searching, and indexed access.

Prefer generic collections over non-generic ArrayList in new code.

Syntax

var names = new List<string> { "Asha", "Dev" };
names.Add("Mira");

Example

Prefer generic collections over non-generic ArrayList in new code.

Code example

var names = new List<string> { "Asha", "Dev" };
names.Add("Mira");

Diagram

Explain generic lists → implementation → result

Key Points

  • List<T> is not thread-safe for concurrent mutation.
Q23Explain key-value collections

What is a dictionary?

Dictionary<TKey,TValue> stores values by unique keys and normally provides fast average lookup.

Answer

Dictionary<TKey,TValue> stores values by unique keys and normally provides fast average lookup.

Use TryGetValue when a key may be absent.

Syntax

var prices = new Dictionary<string, decimal>();
prices["book"] = 12.50m;

Example

Use TryGetValue when a key may be absent.

Code example

var prices = new Dictionary<string, decimal>();
prices["book"] = 12.50m;

Diagram

Explain key-value collections → implementation → result

Key Points

  • Keys must be unique according to the dictionary's equality comparer.
Q24Explain Language Integrated Query

What is LINQ?

LINQ provides a consistent way to query collections and supported data sources using method syntax or query syntax.

Answer

LINQ provides a consistent way to query collections and supported data sources using method syntax or query syntax.

Many LINQ operators are deferred until enumeration; ToList materializes results.

Syntax

var adults = people.Where(p => p.Age >= 18).Select(p => p.Name).ToList();

Example

Many LINQ operators are deferred until enumeration; ToList materializes results.

Code example

var adults = people.Where(p => p.Age >= 18).Select(p => p.Name).ToList();

Diagram

Explain Language Integrated Query → implementation → result

Key Points

  • IQueryable providers may translate expressions to another query language, such as SQL.
Q25Explain lambdas

What is a lambda expression?

A lambda is an anonymous function written with =>. It is commonly used with delegates, LINQ, and callbacks.

Answer

A lambda is an anonymous function written with =>. It is commonly used with delegates, LINQ, and callbacks.

A lambda can capture variables from its surrounding scope.

Syntax

Func<int, int> square = x => x * x;

Example

A lambda can capture variables from its surrounding scope.

Code example

Func<int, int> square = x => x * x;

Diagram

Explain lambdas → implementation → result

Key Points

  • Captured variables can outlive the method where they were declared.
Q26Explain interfaces

What is an interface?

An interface defines a contract that implementing types must satisfy. It enables polymorphism and loose coupling.

Answer

An interface defines a contract that implementing types must satisfy. It enables polymorphism and loose coupling.

A service can depend on ILogger rather than a concrete logger implementation.

Syntax

public interface ILogger { void Log(string message); }

Example

A service can depend on ILogger rather than a concrete logger implementation.

Code example

public interface ILogger { void Log(string message); }

Diagram

Explain interfaces → implementation → result

Key Points

  • Interfaces can include default implementations in modern C#.
Q27Explain inheritance

What is inheritance?

Inheritance lets a derived class reuse and specialize a base class. C# supports single class inheritance and multiple interface implementation.

Answer

Inheritance lets a derived class reuse and specialize a base class. C# supports single class inheritance and multiple interface implementation.

Use inheritance for a genuine is-a relationship; use composition when behavior is assembled from collaborators.

Syntax

public class Animal { public virtual string Speak() => "sound"; }
public class Dog : Animal { public override string Speak() => "woof"; }

Example

Use inheritance for a genuine is-a relationship; use composition when behavior is assembled from collaborators.

Code example

public class Animal { public virtual string Speak() => "sound"; }
public class Dog : Animal { public override string Speak() => "woof"; }

Diagram

Explain inheritance → implementation → result

Key Points

  • All classes ultimately derive from object unless otherwise specified.
Q28Explain polymorphism

What is polymorphism?

Polymorphism lets code call a common contract while the runtime dispatches to the implementation for the actual object.

Answer

Polymorphism lets code call a common contract while the runtime dispatches to the implementation for the actual object.

The call invokes Dog.Speak because it overrides the virtual base method.

Syntax

Animal animal = new Dog();
Console.WriteLine(animal.Speak());

Example

The call invokes Dog.Speak because it overrides the virtual base method.

Code example

Animal animal = new Dog();
Console.WriteLine(animal.Speak());

Diagram

Explain polymorphism → implementation → result

Key Points

  • Overloading is compile-time polymorphism
  • virtual overriding uses runtime dispatch.
Q29Explain encapsulation

What is encapsulation?

Encapsulation keeps internal state and implementation details behind a public contract. It protects invariants by controlling how state changes.

Answer

Encapsulation keeps internal state and implementation details behind a public contract. It protects invariants by controlling how state changes.

Expose behavior such as Deposit rather than a public writable Balance field.

Syntax

public class BankAccount {
  public decimal Balance { get; private set; }
  public void Deposit(decimal amount) {
    if (amount <= 0) throw new ArgumentOutOfRangeException(nameof(amount));
    Balance += amount;
  }
}

Example

Expose behavior such as Deposit rather than a public writable Balance field.

Code example

public class BankAccount {
  public decimal Balance { get; private set; }
  public void Deposit(decimal amount) {
    if (amount <= 0) throw new ArgumentOutOfRangeException(nameof(amount));
    Balance += amount;
  }
}

Diagram

Explain encapsulation → implementation → result

Key Points

  • Encapsulation reduces invalid state and coupling.
Q30Explain abstraction

What is abstraction?

Abstraction exposes essential behavior while hiding implementation details. Interfaces and abstract classes are common tools for defining abstractions.

Answer

Abstraction exposes essential behavior while hiding implementation details. Interfaces and abstract classes are common tools for defining abstractions.

A checkout service can use IPaymentGateway without knowing which provider processes the payment.

Syntax

public interface IPaymentGateway { Task PayAsync(decimal amount); }

Example

A checkout service can use IPaymentGateway without knowing which provider processes the payment.

Code example

public interface IPaymentGateway { Task PayAsync(decimal amount); }

Diagram

Explain abstraction → implementation → result

Key Points

  • A useful abstraction reflects a stable concept, not merely every class needing an interface.
Q31Explain abstract classes

What is an abstract class?

An abstract class cannot be instantiated directly. It can define shared implementation and abstract members that derived classes must implement.

Answer

An abstract class cannot be instantiated directly. It can define shared implementation and abstract members that derived classes must implement.

Use it when related types share implementation or protected state.

Syntax

public abstract class Report {
  public abstract string Render();
}

Example

Use it when related types share implementation or protected state.

Code example

public abstract class Report {
  public abstract string Render();
}

Diagram

Explain abstract classes → implementation → result

Key Points

  • A class can inherit from only one class.
Q32Explain exception handling

What is an exception?

An exception represents an error or unusual condition. try, catch, finally, and throw are used to handle or propagate exceptions.

Answer

An exception represents an error or unusual condition. try, catch, finally, and throw are used to handle or propagate exceptions.

Catch exceptions you can meaningfully handle; preserve context when rethrowing with throw;.

Syntax

try { int n = int.Parse(input); }
catch (FormatException ex) { Console.WriteLine(ex.Message); }

Example

Catch exceptions you can meaningfully handle; preserve context when rethrowing with throw;.

Code example

try { int n = int.Parse(input); }
catch (FormatException ex) { Console.WriteLine(ex.Message); }

Diagram

Explain exception handling → implementation → result

Key Points

  • Avoid using exceptions for ordinary control flow.
Q33Preserve stack traces

What is the difference between throw and throw ex?

Inside a catch block, throw; rethrows the current exception while preserving its original stack trace. throw ex; resets the point from which the stack trac

Answer

Inside a catch block, throw; rethrows the current exception while preserving its original stack trace. throw ex; resets the point from which the stack trace appears to originate.

Use throw; when you need to propagate the same exception.

Syntax

catch (Exception) { throw; }

Example

Use throw; when you need to propagate the same exception.

Code example

catch (Exception) { throw; }

Diagram

Preserve stack traces → implementation → result

Key Points

  • Do not catch and rethrow without adding handling, context, or cleanup.
Q34Explain the .NET GC

What is garbage collection?

The garbage collector reclaims managed objects that are no longer reachable. It uses generations to optimize collection of short-lived objects.

Answer

The garbage collector reclaims managed objects that are no longer reachable. It uses generations to optimize collection of short-lived objects.

GC reduces manual memory management but does not replace disposal of files, sockets, or database connections.

Syntax

var data = new byte[1024]; // eventually eligible when unreachable

Example

GC reduces manual memory management but does not replace disposal of files, sockets, or database connections.

Code example

var data = new byte[1024]; // eventually eligible when unreachable

Diagram

Explain the .NET GC → implementation → result

Key Points

  • Collection timing is nondeterministic.
Q35Explain deterministic cleanup

What is IDisposable?

IDisposable provides a Dispose method for releasing resources deterministically. Use using or await using to ensure cleanup even when exceptions occur.

Answer

IDisposable provides a Dispose method for releasing resources deterministically. Use using or await using to ensure cleanup even when exceptions occur.

Database connections and file streams commonly implement IDisposable.

Syntax

using var stream = File.OpenRead(path);

Example

Database connections and file streams commonly implement IDisposable.

Code example

using var stream = File.OpenRead(path);

Diagram

Explain deterministic cleanup → implementation → result

Key Points

  • Dispose is different from garbage collection
  • it releases resources promptly.
Q36Explain static members

What is a static member?

A static member belongs to the type rather than a particular instance. Static methods cannot directly access instance members without an object reference.

Answer

A static member belongs to the type rather than a particular instance. Static methods cannot directly access instance members without an object reference.

Use static methods for operations with no per-instance state.

Syntax

public static class MathTools { public static int Double(int x) => x * 2; }

Example

Use static methods for operations with no per-instance state.

Code example

public static class MathTools { public static int Double(int x) => x * 2; }

Diagram

Explain static members → implementation → result

Key Points

  • Avoid global mutable static state because it complicates tests and concurrency.
Q37Explain generics

What is a generic type?

Generics let types and methods work with parameters representing types, preserving compile-time type safety and reducing casts.

Answer

Generics let types and methods work with parameters representing types, preserving compile-time type safety and reducing casts.

var box = new Box<int> { Value = 5 };

Syntax

public class Box<T> { public T Value { get; set; } = default!; }

Example

var box = new Box<int> { Value = 5 };

Code example

public class Box<T> { public T Value { get; set; } = default!; }

Diagram

Explain generics → implementation → result

Key Points

  • Generic constraints can restrict which types are valid.
Q38Explain asynchronous programming

What is async and await?

async and await let a method await an asynchronous operation without blocking a thread while that operation is pending. They are especially useful for I/O-

Answer

async and await let a method await an asynchronous operation without blocking a thread while that operation is pending. They are especially useful for I/O-bound work.

Use asynchronous APIs end-to-end for database, network, and file I/O.

Syntax

public async Task<string> ReadAsync(string path) => await File.ReadAllTextAsync(path);

Example

Use asynchronous APIs end-to-end for database, network, and file I/O.

Code example

public async Task<string> ReadAsync(string path) => await File.ReadAllTextAsync(path);

Diagram

Explain asynchronous programming → implementation → result

Key Points

  • async does not automatically create a new thread.
Q39Explain Task and Task<T>

What is Task<T>?

Task represents an asynchronous operation that completes in the future. Task<T> also provides a result of type T.

Answer

Task represents an asynchronous operation that completes in the future. Task<T> also provides a result of type T.

Use Task for asynchronous methods; avoid async void except event handlers.

Syntax

Task<int> work = Task.FromResult(42);

Example

Use Task for asynchronous methods; avoid async void except event handlers.

Code example

Task<int> work = Task.FromResult(42);

Diagram

Explain Task and Task<T> → implementation → result

Key Points

  • A Task can complete successfully, fault, or be cancelled.
Q40Explain delegates

What is a delegate?

A delegate is a type-safe reference to a method or compatible callable target. Func, Action, and Predicate are common built-in delegate types.

Answer

A delegate is a type-safe reference to a method or compatible callable target. Func, Action, and Predicate are common built-in delegate types.

Delegates power callbacks and events.

Syntax

Action<string> print = message => Console.WriteLine(message);
print("Hello");

Example

Delegates power callbacks and events.

Code example

Action<string> print = message => Console.WriteLine(message);
print("Hello");

Diagram

Explain delegates → implementation → result

Key Points

  • Func<T,..., TResult> returns a value
  • Action<T...> returns void.
Q41Explain events

What is an event?

An event provides a publisher/subscriber pattern around a delegate. Subscribers can react to a notification without the publisher knowing their concrete im

Answer

An event provides a publisher/subscriber pattern around a delegate. Subscribers can react to a notification without the publisher knowing their concrete implementations.

Unsubscribe long-lived publishers when needed to avoid retaining subscribers unintentionally.

Syntax

public event EventHandler? Saved;
Saved?.Invoke(this, EventArgs.Empty);

Example

Unsubscribe long-lived publishers when needed to avoid retaining subscribers unintentionally.

Code example

public event EventHandler? Saved;
Saved?.Invoke(this, EventArgs.Empty);

Diagram

Explain events → implementation → result

Key Points

  • Events restrict external code from invoking the event directly.
Q42Explain ASP.NET Core

What is ASP.NET Core?

ASP.NET Core is a cross-platform framework for building web apps, REST APIs, real-time apps, and services on .NET. It uses middleware and dependency inject

Answer

ASP.NET Core is a cross-platform framework for building web apps, REST APIs, real-time apps, and services on .NET. It uses middleware and dependency injection.

Kestrel is the built-in cross-platform web server; it can run behind a reverse proxy.

Syntax

dotnet new webapi -n CatalogApi
cd CatalogApi
dotnet run

Example

Kestrel is the built-in cross-platform web server; it can run behind a reverse proxy.

Code example

dotnet new webapi -n CatalogApi
cd CatalogApi
dotnet run

Diagram

Explain ASP.NET Core → implementation → result

Key Points

  • ASP.NET Core is distinct from legacy ASP.NET on .NET Framework.
Q43Explain the middleware pipeline

What is middleware?

Middleware components process HTTP requests and responses in sequence. Each component can call the next component or short-circuit the pipeline.

Answer

Middleware components process HTTP requests and responses in sequence. Each component can call the next component or short-circuit the pipeline.

Ordering matters: exception handling, routing, authentication, and authorization should be arranged appropriately.

Syntax

app.Use(async (context, next) => {
  Console.WriteLine("Before");
  await next();
  Console.WriteLine("After");
});

Example

Ordering matters: exception handling, routing, authentication, and authorization should be arranged appropriately.

Code example

app.Use(async (context, next) => {
  Console.WriteLine("Before");
  await next();
  Console.WriteLine("After");
});

Diagram

Explain the middleware pipeline → implementation → result

Key Points

  • A component that never calls next ends the downstream pipeline.
Q44Explain API controllers

What is a controller in ASP.NET Core Web API?

A controller groups HTTP endpoints into action methods. Controllers commonly use attributes such as [ApiController], [Route], and [HttpGet].

Answer

A controller groups HTTP endpoints into action methods. Controllers commonly use attributes such as [ApiController], [Route], and [HttpGet].

ControllerBase is intended for APIs and does not include view support.

Syntax

[ApiController]
[Route("api/products")]
public class ProductsController : ControllerBase {
  [HttpGet]
  public IActionResult Get() => Ok(new[] { "Pen", "Book" });
}

Example

ControllerBase is intended for APIs and does not include view support.

Code example

[ApiController]
[Route("api/products")]
public class ProductsController : ControllerBase {
  [HttpGet]
  public IActionResult Get() => Ok(new[] { "Pen", "Book" });
}

Diagram

Explain API controllers → implementation → result

Key Points

  • Return appropriate HTTP status codes and DTOs.
Q45Explain REST-style APIs

What is a REST API?

A REST-style API exposes resources through URLs and uses HTTP methods and status codes. Statelessness and consistent resource representations are important

Answer

A REST-style API exposes resources through URLs and uses HTTP methods and status codes. Statelessness and consistent resource representations are important principles.

GET retrieves; POST creates or triggers processing; PUT replaces; PATCH partially updates; DELETE removes.

Syntax

GET /api/products/42
POST /api/products

Example

GET retrieves; POST creates or triggers processing; PUT replaces; PATCH partially updates; DELETE removes.

Code example

GET /api/products/42
POST /api/products

Diagram

Explain REST-style APIs → implementation → result

Key Points

  • REST is an architectural style, not a specific library.
Q126C#

When should you use a record instead of a class?

Records are designed for value-oriented data models and provide value-based equality by default. Classes normally use reference identity unless e

Answer

Records are designed for value-oriented data models and provide value-based equality by default. Classes normally use reference identity unless equality is overridden.

Apply the approach according to the application's constraints and verify important behavior with automated tests.

Syntax

public record Person(string Name, int Age);

Example

var first = new Person("Mia", 30); var second = new Person("Mia", 30); Console.WriteLine(first == second); // True

Code example

public record Person(string Name, int Age);\nvar first = new Person("Mia", 30);\nvar second = new Person("Mia", 30);\nConsole.WriteLine(first == second); // True

Diagram

Create two records with identical values → value equality returns true.

Key Points

  • Records are designed for value-oriented data models and provide value-based equality by default.
  • Keep dependencies and responsibilities explicit.
  • Cover error handling and edge cases in tests.
Q130OOP

What is composition and why can it be preferable to inheritance?

Composition builds behavior by holding references to collaborating objects. It reduces tight coupling to a base-class hierarchy and makes behavio

Answer

Composition builds behavior by holding references to collaborating objects. It reduces tight coupling to a base-class hierarchy and makes behavior easier to replace and test.

Apply the approach according to the application's constraints and verify important behavior with automated tests.

Syntax

class Car { private readonly IEngine _engine; }

Example

public interface IEngine { void Start(); } public sealed class Car(IEngine engine) { public void Start() => engine.Start(); }

Code example

public interface IEngine { void Start(); }\npublic sealed class Car(IEngine engine)\n{\n    public void Start() => engine.Start();\n}

Diagram

Car → IEngine interface → concrete engine implementation.

Key Points

  • Composition builds behavior by holding references to collaborating objects.
  • Keep dependencies and responsibilities explicit.
  • Cover error handling and edge cases in tests.

Intermediate Questions

Implementation details, practical patterns, and common workflows.

Q46Explain DI and service lifetimes

What is dependency injection?

Dependency injection supplies a class's dependencies from outside instead of constructing them internally. ASP.NET Core has a built-in service container.

Answer

Dependency injection supplies a class's dependencies from outside instead of constructing them internally. ASP.NET Core has a built-in service container.

DI improves testability and separates construction from business logic.

Syntax

builder.Services.AddScoped<IProductService, ProductService>();
public ProductsController(IProductService service) { _service = service; }

Example

DI improves testability and separates construction from business logic.

Code example

builder.Services.AddScoped<IProductService, ProductService>();
public ProductsController(IProductService service) { _service = service; }

Diagram

Explain DI and service lifetimes → implementation → result

Key Points

  • Transient creates each resolution
  • scoped is one per request scope
  • singleton is one per container.
Q47Choose DI lifetimes

Compare transient, scoped, and singleton lifetimes.

Transient creates a new instance each time it is requested; scoped creates one instance per scope, typically an HTTP request; singleton lives for the servi

Answer

Transient creates a new instance each time it is requested; scoped creates one instance per scope, typically an HTTP request; singleton lives for the service provider's lifetime.

DbContext is normally scoped. Do not inject a scoped service directly into a singleton.

Syntax

services.AddTransient<IFormatter, Formatter>();
services.AddScoped<IOrderService, OrderService>();
services.AddSingleton<IClock, SystemClock>();

Example

DbContext is normally scoped. Do not inject a scoped service directly into a singleton.

Code example

services.AddTransient<IFormatter, Formatter>();
services.AddScoped<IOrderService, OrderService>();
services.AddSingleton<IClock, SystemClock>();

Diagram

Choose DI lifetimes → implementation → result

Key Points

  • A singleton must be thread-safe if used concurrently.
Q48Diagnose a lifetime mismatch

What is a captive dependency?

A captive dependency occurs when a long-lived service captures a shorter-lived dependency, such as a singleton holding a scoped DbContext. This can cause s

Answer

A captive dependency occurs when a long-lived service captures a shorter-lived dependency, such as a singleton holding a scoped DbContext. This can cause stale state or incorrect cross-request sharing.

Use IServiceScopeFactory to create a scope for bounded work when appropriate, or align the lifetimes.

Syntax

// Avoid: singleton service -> scoped DbContext
services.AddSingleton<ReportService>();

Example

Use IServiceScopeFactory to create a scope for bounded work when appropriate, or align the lifetimes.

Code example

// Avoid: singleton service -> scoped DbContext
services.AddSingleton<ReportService>();

Diagram

Diagnose a lifetime mismatch → implementation → result

Key Points

  • Enable scope validation in development to catch common mistakes.
Q49Bind configuration to typed settings

What is the options pattern?

The options pattern binds configuration to a typed class and supports validation and different lifetimes through IOptions, IOptionsSnapshot, and IOptionsMo

Answer

The options pattern binds configuration to a typed class and supports validation and different lifetimes through IOptions, IOptionsSnapshot, and IOptionsMonitor.

Use strongly typed options rather than scattering configuration string keys.

Syntax

builder.Services.AddOptions<MailOptions>()
  .BindConfiguration("Mail")
  .ValidateDataAnnotations()
  .ValidateOnStart();

Example

Use strongly typed options rather than scattering configuration string keys.

Code example

builder.Services.AddOptions<MailOptions>()
  .BindConfiguration("Mail")
  .ValidateDataAnnotations()
  .ValidateOnStart();

Diagram

Bind configuration to typed settings → implementation → result

Key Points

  • IOptionsSnapshot is scoped
  • IOptionsMonitor supports change notifications.
Q50Describe configuration providers

How does configuration work in ASP.NET Core?

Configuration can come from JSON files, environment variables, command-line arguments, secret stores, and custom providers. Later providers can override ea

Answer

Configuration can come from JSON files, environment variables, command-line arguments, secret stores, and custom providers. Later providers can override earlier values according to provider ordering.

Keep production secrets out of committed appsettings.json; use environment variables or a secret manager.

Syntax

var connection = builder.Configuration.GetConnectionString("Default");

Example

Keep production secrets out of committed appsettings.json; use environment variables or a secret manager.

Code example

var connection = builder.Configuration.GetConnectionString("Default");

Diagram

Describe configuration providers → implementation → result

Key Points

  • Configuration key names are commonly hierarchical, e.g. Mail:Host.
Q51Compare configuration sources

What is the difference between appsettings.json and environment variables?

appsettings.json provides baseline settings. Environment variables are useful for deployment-specific overrides and secret injection by the hosting platfor

Answer

appsettings.json provides baseline settings. Environment variables are useful for deployment-specific overrides and secret injection by the hosting platform.

Double underscore commonly maps to a colon in hierarchical configuration keys.

Syntax

ConnectionStrings__Default="Server=...;Database=..."

Example

Double underscore commonly maps to a colon in hierarchical configuration keys.

Code example

ConnectionStrings__Default="Server=...;Database=..."

Diagram

Compare configuration sources → implementation → result

Key Points

  • Protect environment variables and logs
  • they are not inherently a secret vault.
Q52Build centralized error handling

How do you implement global exception handling?

Use exception-handling middleware or IExceptionHandler to map unexpected exceptions to consistent ProblemDetails responses. Log details internally and avoi

Answer

Use exception-handling middleware or IExceptionHandler to map unexpected exceptions to consistent ProblemDetails responses. Log details internally and avoid exposing stack traces to clients.

Return safe error messages with a trace identifier for support.

Syntax

app.UseExceptionHandler();
// Configure ProblemDetails services as appropriate for the target .NET version.

Example

Return safe error messages with a trace identifier for support.

Code example

app.UseExceptionHandler();
// Configure ProblemDetails services as appropriate for the target .NET version.

Diagram

Build centralized error handling → implementation → result

Key Points

  • Do not expose connection strings, SQL text, or stack traces in production responses.
Q53Standardize API errors

What is ProblemDetails?

ProblemDetails is a standard representation for HTTP API errors, with fields such as type, title, status, detail, and instance. ASP.NET Core can generate i

Answer

ProblemDetails is a standard representation for HTTP API errors, with fields such as type, title, status, detail, and instance. ASP.NET Core can generate it for common error responses.

Use stable machine-readable error codes or extensions where clients need programmatic handling.

Syntax

return Problem(title: "Product not found", statusCode: 404);

Example

Use stable machine-readable error codes or extensions where clients need programmatic handling.

Code example

return Problem(title: "Product not found", statusCode: 404);

Diagram

Standardize API errors → implementation → result

Key Points

  • Do not put sensitive internal exception details in detail.
Q54Explain binding HTTP data to parameters

What is model binding?

Model binding maps route values, query strings, headers, and request bodies to action parameters or model properties. Validation runs after binding for sup

Answer

Model binding maps route values, query strings, headers, and request bodies to action parameters or model properties. Validation runs after binding for supported models.

Use explicit binding attributes when the source should be clear.

Syntax

public IActionResult Search([FromQuery] string term, [FromQuery] int page = 1)

Example

Use explicit binding attributes when the source should be clear.

Code example

public IActionResult Search([FromQuery] string term, [FromQuery] int page = 1)

Diagram

Explain binding HTTP data to parameters → implementation → result

Key Points

  • A request body is normally read once
  • avoid multiple body-bound parameters.
Q55Validate request DTOs

How does model validation work?

Validation uses attributes such as [Required], [Range], and custom validators. With [ApiController], invalid model state normally produces an automatic 400

Answer

Validation uses attributes such as [Required], [Range], and custom validators. With [ApiController], invalid model state normally produces an automatic 400 response.

Validation is not a substitute for authorization or business-rule checks.

Syntax

public sealed class CreateProductRequest {
  [Required, StringLength(100)] public string Name { get; init; } = "";
  [Range(0.01, 100000)] public decimal Price { get; init; }
}

Example

Validation is not a substitute for authorization or business-rule checks.

Code example

public sealed class CreateProductRequest {
  [Required, StringLength(100)] public string Name { get; init; } = "";
  [Range(0.01, 100000)] public decimal Price { get; init; }
}

Diagram

Validate request DTOs → implementation → result

Key Points

  • Validate domain invariants in the domain/application layer as well.
Q56Choose controller return types

What is the difference between IActionResult and ActionResult<T>?

IActionResult can represent many HTTP responses. ActionResult<T> combines a typed success result with alternative IActionResult responses and improves API

Answer

IActionResult can represent many HTTP responses. ActionResult<T> combines a typed success result with alternative IActionResult responses and improves API metadata.

Use typed results where they improve API clarity and OpenAPI generation.

Syntax

public ActionResult<ProductDto> Get(int id) {
  var item = Find(id);
  return item is null ? NotFound() : Ok(item);
}

Example

Use typed results where they improve API clarity and OpenAPI generation.

Code example

public ActionResult<ProductDto> Get(int id) {
  var item = Find(id);
  return item is null ? NotFound() : Ok(item);
}

Diagram

Choose controller return types → implementation → result

Key Points

  • Minimal APIs use IResult and typed result helpers.
Q57Separate API contracts from persistence models

How do you design DTOs?

DTOs define what the API accepts or returns. They avoid exposing database entities directly and let the API evolve without leaking internal persistence det

Answer

DTOs define what the API accepts or returns. They avoid exposing database entities directly and let the API evolve without leaking internal persistence details.

Use separate input and output DTOs when their rules differ.

Syntax

public record ProductDto(int Id, string Name, decimal Price);
public record CreateProductRequest(string Name, decimal Price);

Example

Use separate input and output DTOs when their rules differ.

Code example

public record ProductDto(int Id, string Name, decimal Price);
public record CreateProductRequest(string Name, decimal Price);

Diagram

Separate API contracts from persistence models → implementation → result

Key Points

  • Never rely on hiding sensitive entity properties only in the UI.
Q58Explain EF Core

What is Entity Framework Core?

EF Core is an object-relational mapper that lets .NET code query and update relational databases using entity classes and LINQ. It translates supported que

Answer

EF Core is an object-relational mapper that lets .NET code query and update relational databases using entity classes and LINQ. It translates supported queries to provider-specific SQL.

Use migrations to manage schema changes and inspect generated SQL for important queries.

Syntax

builder.Services.AddDbContext<AppDbContext>(o => o.UseSqlServer(connectionString));

Example

Use migrations to manage schema changes and inspect generated SQL for important queries.

Code example

builder.Services.AddDbContext<AppDbContext>(o => o.UseSqlServer(connectionString));

Diagram

Explain EF Core → implementation → result

Key Points

  • EF Core is not a database
  • it uses a provider to connect to one.
Q59Explain unit-of-work behavior

What is DbContext and why is it scoped?

DbContext represents a session with the database and tracks changes to entities. It is designed for a short unit of work and is not thread-safe.

Answer

DbContext represents a session with the database and tracks changes to entities. It is designed for a short unit of work and is not thread-safe.

Do not share one DbContext across concurrent tasks or unrelated requests.

Syntax

await using var db = await factory.CreateDbContextAsync();

Example

Do not share one DbContext across concurrent tasks or unrelated requests.

Code example

await using var db = await factory.CreateDbContextAsync();

Diagram

Explain unit-of-work behavior → implementation → result

Key Points

  • A scoped DbContext is the common web-app registration.
Q60Explain tracked entities

What is change tracking in EF Core?

EF Core tracks entity states such as Added, Modified, Deleted, and Unchanged. SaveChanges generates database commands based on those states.

Answer

EF Core tracks entity states such as Added, Modified, Deleted, and Unchanged. SaveChanges generates database commands based on those states.

AsNoTracking is useful for read-only queries where tracking is unnecessary.

Syntax

var product = await db.Products.FindAsync(id);
product!.Price = 19.99m;
await db.SaveChangesAsync();

Example

AsNoTracking is useful for read-only queries where tracking is unnecessary.

Code example

var product = await db.Products.FindAsync(id);
product!.Price = 19.99m;
await db.SaveChangesAsync();

Diagram

Explain tracked entities → implementation → result

Key Points

  • Tracked entity changes are not persisted until SaveChanges succeeds.
Q61Compare navigation loading strategies

What is eager, explicit, and lazy loading?

Eager loading fetches related data as part of the query using Include. Explicit loading fetches it on demand. Lazy loading loads navigation data when acces

Answer

Eager loading fetches related data as part of the query using Include. Explicit loading fetches it on demand. Lazy loading loads navigation data when accessed if configured.

Prefer deliberate loading to avoid N+1 query problems.

Syntax

var orders = await db.Orders.Include(o => o.Items).ToListAsync();

Example

Prefer deliberate loading to avoid N+1 query problems.

Code example

var orders = await db.Orders.Include(o => o.Items).ToListAsync();

Diagram

Compare navigation loading strategies → implementation → result

Key Points

  • Lazy loading can hide database round trips inside property access.
Q62Detect inefficient data access

What is the N+1 query problem?

N+1 occurs when one query loads a set of rows and then an additional query runs for each row to load related data. It increases latency and database load.

Answer

N+1 occurs when one query loads a set of rows and then an additional query runs for each row to load related data. It increases latency and database load.

Project only the fields needed, use Include when appropriate, and inspect SQL logs or tracing.

Syntax

// Prefer Include/projection instead of querying children inside a loop.

Example

Project only the fields needed, use Include when appropriate, and inspect SQL logs or tracing.

Code example

// Prefer Include/projection instead of querying children inside a loop.

Diagram

Detect inefficient data access → implementation → result

Key Points

  • More joins are not always better
  • verify query shape and result size.
Q63Manage database schema changes

What are EF Core migrations?

Migrations record incremental schema changes based on model differences. They can be reviewed and applied in controlled deployment processes.

Answer

Migrations record incremental schema changes based on model differences. They can be reviewed and applied in controlled deployment processes.

Review generated migrations before applying them to production.

Syntax

dotnet ef migrations add AddProductSku
dotnet ef database update

Example

Review generated migrations before applying them to production.

Code example

dotnet ef migrations add AddProductSku
dotnet ef database update

Diagram

Manage database schema changes → implementation → result

Key Points

  • Coordinate schema changes with application rollout and rollback strategy.
Q64Use parameterized database access

How do you prevent SQL injection?

SQL injection happens when untrusted input is concatenated into SQL syntax. Use parameterized queries or EF Core LINQ; avoid building SQL by string concate

Answer

SQL injection happens when untrusted input is concatenated into SQL syntax. Use parameterized queries or EF Core LINQ; avoid building SQL by string concatenation.

For raw SQL, use parameterized APIs and never interpolate untrusted values as SQL syntax.

Syntax

var product = await db.Products.FirstOrDefaultAsync(p => p.Id == id);

Example

For raw SQL, use parameterized APIs and never interpolate untrusted values as SQL syntax.

Code example

var product = await db.Products.FirstOrDefaultAsync(p => p.Id == id);

Diagram

Use parameterized database access → implementation → result

Key Points

  • Parameters represent values, not table or column identifiers.
Q65Explain query evaluation timing

What is LINQ deferred execution?

Many LINQ queries build an iterator or expression and run only when enumerated. Operators such as ToList, ToArray, Count, or foreach trigger execution.

Answer

Many LINQ queries build an iterator or expression and run only when enumerated. Operators such as ToList, ToArray, Count, or foreach trigger execution.

A deferred query can observe later changes to the source collection and may execute more than once.

Syntax

var query = numbers.Where(n => n > 10); // not necessarily evaluated yet
var results = query.ToList();

Example

A deferred query can observe later changes to the source collection and may execute more than once.

Code example

var query = numbers.Where(n => n > 10); // not necessarily evaluated yet
var results = query.ToList();

Diagram

Explain query evaluation timing → implementation → result

Key Points

  • IQueryable may execute a database query each time it is enumerated.
Q66Compare LINQ abstractions

What is the difference between IEnumerable and IQueryable?

IEnumerable represents in-memory or streamed enumeration using delegates. IQueryable carries an expression tree that a provider may translate, for example

Answer

IEnumerable represents in-memory or streamed enumeration using delegates. IQueryable carries an expression tree that a provider may translate, for example into SQL.

Keep filtering and projection server-side until the required data has been narrowed.

Syntax

IQueryable<Product> q = db.Products.Where(p => p.Price > 10);
var result = await q.ToListAsync();

Example

Keep filtering and projection server-side until the required data has been narrowed.

Code example

IQueryable<Product> q = db.Products.Where(p => p.Price > 10);
var result = await q.ToListAsync();

Diagram

Compare LINQ abstractions → implementation → result

Key Points

  • Calling AsEnumerable changes subsequent operators to client-side LINQ.
Q67Improve I/O scalability

What is async I/O and why use it in APIs?

Asynchronous I/O lets request threads return to the pool while waiting on network, database, or file operations. It improves scalability under I/O load but

Answer

Asynchronous I/O lets request threads return to the pool while waiting on network, database, or file operations. It improves scalability under I/O load but does not make CPU-heavy work faster by itself.

Use async database and HTTP APIs end-to-end and pass cancellation tokens.

Syntax

var product = await db.Products.FindAsync(id, cancellationToken);

Example

Use async database and HTTP APIs end-to-end and pass cancellation tokens.

Code example

var product = await db.Products.FindAsync(id, cancellationToken);

Diagram

Improve I/O scalability → implementation → result

Key Points

  • Avoid .Result and .Wait in request paths because they block threads and can cause starvation.
Q68Use Task-returning async methods

Why should async void be avoided?

async void cannot be awaited by callers and its exceptions cannot be observed through a returned Task. It is generally reserved for event handlers.

Answer

async void cannot be awaited by callers and its exceptions cannot be observed through a returned Task. It is generally reserved for event handlers.

Return Task or Task<T> from asynchronous service methods.

Syntax

public async Task SaveAsync() { await repository.SaveAsync(); }

Example

Return Task or Task<T> from asynchronous service methods.

Code example

public async Task SaveAsync() { await repository.SaveAsync(); }

Diagram

Use Task-returning async methods → implementation → result

Key Points

  • Fire-and-forget work needs deliberate lifetime, error handling, and observability.
Q69Support cooperative cancellation

What is CancellationToken?

CancellationToken communicates a cancellation request. APIs should pass it through to database, HTTP, and other operations when supported.

Answer

CancellationToken communicates a cancellation request. APIs should pass it through to database, HTTP, and other operations when supported.

Use HttpContext.RequestAborted for work tied to a client request where appropriate.

Syntax

public Task<Product?> GetAsync(int id, CancellationToken ct) => db.Products.FirstOrDefaultAsync(p => p.Id == id, ct);

Example

Use HttpContext.RequestAborted for work tied to a client request where appropriate.

Code example

public Task<Product?> GetAsync(int id, CancellationToken ct) => db.Products.FirstOrDefaultAsync(p => p.Id == id, ct);

Diagram

Support cooperative cancellation → implementation → result

Key Points

  • Cancellation is cooperative
  • a token does not forcibly stop arbitrary code.
Q70Explain continuation context

What is ConfigureAwait(false)?

ConfigureAwait(false) tells an await not to require resuming on the captured synchronization context. It can matter in reusable libraries, while ASP.NET Co

Answer

ConfigureAwait(false) tells an await not to require resuming on the captured synchronization context. It can matter in reusable libraries, while ASP.NET Core generally has no classic request synchronization context.

Use based on library/runtime context and team conventions rather than applying mechanically everywhere.

Syntax

await operation.ConfigureAwait(false);

Example

Use based on library/runtime context and team conventions rather than applying mechanically everywhere.

Code example

await operation.ConfigureAwait(false);

Diagram

Explain continuation context → implementation → result

Key Points

  • It does not mean run on a new thread.
Q71Use HttpClientFactory

How do you call another API with HttpClient?

Use IHttpClientFactory or a typed client to manage HttpClient instances and configuration. Set timeouts, cancellation, and resilient handling appropriate t

Answer

Use IHttpClientFactory or a typed client to manage HttpClient instances and configuration. Set timeouts, cancellation, and resilient handling appropriate to the downstream service.

Use typed clients for a clear contract and central configuration.

Diagram / flow: builder.Services.AddHttpClient<InventoryClient>(c => c.BaseAddress = new Uri("https://inventory.example/")); var response = await client.GetAsync("api/stock", ct); response.EnsureSuccessStatusCode();

Syntax

builder.Services.AddHttpClient<InventoryClient>(c => c.BaseAddress = new Uri("https://inventory.example/"));
var response = await client.GetAsync("api/stock", ct);
response.EnsureSuccessStatusCode();

Example

Use typed clients for a clear contract and central configuration.

Code example

builder.Services.AddHttpClient<InventoryClient>(c => c.BaseAddress = new Uri("https://inventory.example/"));
var response = await client.GetAsync("api/stock", ct);
response.EnsureSuccessStatusCode();

Diagram

Diagram / flow:
builder.Services.AddHttpClient<InventoryClient>(c => c.BaseAddress = new Uri("https://inventory.example/"));
var response = await client.GetAsync("api/stock", ct);
response.EnsureSuccessStatusCode();

Key Points

  • Do not create and dispose a new HttpClient for every request.
Q72Add resilient HTTP policies

How do you configure retries for HTTP calls?

Retries can help with transient failures, but should be bounded, use backoff and jitter, and respect idempotency and server guidance. Modern .NET resilienc

Answer

Retries can help with transient failures, but should be bounded, use backoff and jitter, and respect idempotency and server guidance. Modern .NET resilience handlers can be registered through supported resilience packages.

Avoid retrying non-idempotent operations blindly; consider Retry-After and an overall timeout.

Diagram / flow: // Register a supported resilience handler for the named/typed HttpClient.

Syntax

// Register a supported resilience handler for the named/typed HttpClient.

Example

Avoid retrying non-idempotent operations blindly; consider Retry-After and an overall timeout.

Code example

// Register a supported resilience handler for the named/typed HttpClient.

Diagram

Diagram / flow:
// Register a supported resilience handler for the named/typed HttpClient.

Key Points

  • Retries can amplify an outage if used without limits.
Q73Explain method semantics

What are REST HTTP methods and idempotency?

GET is safe and idempotent by convention; PUT and DELETE are idempotent in intended effect; POST is generally not idempotent. PATCH applies partial modific

Answer

GET is safe and idempotent by convention; PUT and DELETE are idempotent in intended effect; POST is generally not idempotent. PATCH applies partial modifications and its idempotency depends on the operation.

Design create/payment endpoints with idempotency keys when clients may retry.

Syntax

PUT /api/products/42
DELETE /api/products/42

Example

Design create/payment endpoints with idempotency keys when clients may retry.

Code example

PUT /api/products/42
DELETE /api/products/42

Diagram

Explain method semantics → implementation → result

Key Points

  • Idempotency describes effect, not whether the same response body is returned.
Q74Choose status codes

Which HTTP status codes should an API use?

Common codes include 200 OK, 201 Created, 204 No Content, 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 409 Conflict, 422 Unprocessable

Answer

Common codes include 200 OK, 201 Created, 204 No Content, 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 409 Conflict, 422 Unprocessable Content where adopted, and 500 Internal Server Error.

Use 401 when authentication is missing/invalid and 403 when the authenticated caller lacks permission.

Syntax

return CreatedAtAction(nameof(GetById), new { id = product.Id }, product);

Example

Use 401 when authentication is missing/invalid and 403 when the authenticated caller lacks permission.

Code example

return CreatedAtAction(nameof(GetById), new { id = product.Id }, product);

Diagram

Choose status codes → implementation → result

Key Points

  • Be consistent and document error contracts.
Q75Distinguish identity from permissions

What is authentication versus authorization?

Authentication establishes who the caller is. Authorization determines what the caller is allowed to do.

Answer

Authentication establishes who the caller is. Authorization determines what the caller is allowed to do.

Use policies and roles/claims to enforce access to endpoints and resources.

Syntax

builder.Services.AddAuthentication().AddJwtBearer();
app.UseAuthentication();
app.UseAuthorization();

Example

Use policies and roles/claims to enforce access to endpoints and resources.

Code example

builder.Services.AddAuthentication().AddJwtBearer();
app.UseAuthentication();
app.UseAuthorization();

Diagram

Distinguish identity from permissions → implementation → result

Key Points

  • A valid token does not automatically authorize every action.
Q76Explain JSON Web Tokens

What is JWT?

A JWT is a compact token format that can carry claims and is often signed. APIs validate signature, issuer, audience, and lifetime before trusting claims.

Answer

A JWT is a compact token format that can carry claims and is often signed. APIs validate signature, issuer, audience, and lifetime before trusting claims.

Never put secrets in JWT payloads; signed JWT payloads are typically readable.

Syntax

Authorization: Bearer <access-token>

Example

Never put secrets in JWT payloads; signed JWT payloads are typically readable.

Code example

Authorization: Bearer <access-token>

Diagram

Explain JSON Web Tokens → implementation → result

Key Points

  • JWT is a token format, not an authentication protocol by itself.
Q77Compare delegated authorization and identity

What is OAuth 2.0 and OpenID Connect?

OAuth 2.0 is an authorization framework for delegated access. OpenID Connect adds an identity layer on top of OAuth 2.0. APIs typically validate access tok

Answer

OAuth 2.0 is an authorization framework for delegated access. OpenID Connect adds an identity layer on top of OAuth 2.0. APIs typically validate access tokens; clients use OIDC for sign-in.

Use Authorization Code with PKCE for interactive public clients and a trusted identity provider.

Syntax

// Configure the appropriate OIDC/OAuth provider and validate tokens server-side.

Example

Use Authorization Code with PKCE for interactive public clients and a trusted identity provider.

Code example

// Configure the appropriate OIDC/OAuth provider and validate tokens server-side.

Diagram

Compare delegated authorization and identity → implementation → result

Key Points

  • Do not implement token validation by merely decoding the token.
Q78Protect endpoints with policies

How do you implement role or policy authorization?

Define authorization policies and apply them to endpoints or controllers. Policies can evaluate roles, claims, and custom requirements.

Answer

Define authorization policies and apply them to endpoints or controllers. Policies can evaluate roles, claims, and custom requirements.

Policies centralize access rules and can be unit tested.

Syntax

builder.Services.AddAuthorization(o => o.AddPolicy("CanManageProducts", p => p.RequireRole("Admin")));
[Authorize(Policy = "CanManageProducts")]

Example

Policies centralize access rules and can be unit tested.

Code example

builder.Services.AddAuthorization(o => o.AddPolicy("CanManageProducts", p => p.RequireRole("Admin")));
[Authorize(Policy = "CanManageProducts")]

Diagram

Protect endpoints with policies → implementation → result

Key Points

  • Resource ownership often requires checking the specific resource, not just a broad role.
Q79Explain cross-origin requests

What is CORS?

Cross-Origin Resource Sharing is a browser-enforced mechanism controlled by response headers that determines whether a web page from another origin can rea

Answer

Cross-Origin Resource Sharing is a browser-enforced mechanism controlled by response headers that determines whether a web page from another origin can read a response.

Allow only trusted origins and configure credentials carefully.

Syntax

builder.Services.AddCors(o => o.AddPolicy("Frontend", p => p.WithOrigins("https://app.example.com").AllowAnyHeader().AllowAnyMethod()));

Example

Allow only trusted origins and configure credentials carefully.

Code example

builder.Services.AddCors(o => o.AddPolicy("Frontend", p => p.WithOrigins("https://app.example.com").AllowAnyHeader().AllowAnyMethod()));

Diagram

Explain cross-origin requests → implementation → result

Key Points

  • CORS is not an API authentication mechanism and does not block non-browser clients.
Q80Manage application secrets

How do you secure secrets in ASP.NET Core?

Use development user secrets locally and a managed secret store or platform-provided secure configuration in production. Rotate credentials and restrict ac

Answer

Use development user secrets locally and a managed secret store or platform-provided secure configuration in production. Rotate credentials and restrict access.

Avoid committing secrets, printing them in logs, or embedding them in frontend code.

Syntax

dotnet user-secrets init
dotnet user-secrets set "Mail:ApiKey" "local-development-value"

Example

Avoid committing secrets, printing them in logs, or embedding them in frontend code.

Code example

dotnet user-secrets init
dotnet user-secrets set "Mail:ApiKey" "local-development-value"

Diagram

Manage application secrets → implementation → result

Key Points

  • Environment variables are a delivery mechanism, not always a full secret-management solution.
Q81Explain repository abstraction

What is the repository pattern?

A repository presents a collection-like interface for domain persistence and can isolate complex data access. EF Core DbContext already provides repository

Answer

A repository presents a collection-like interface for domain persistence and can isolate complex data access. EF Core DbContext already provides repository/unit-of-work-like behavior, so an extra layer should add value.

Use repositories when they clarify domain boundaries or isolate persistence, not automatically for every DbSet.

Syntax

public interface IProductRepository { Task<Product?> GetAsync(int id, CancellationToken ct); }

Example

Use repositories when they clarify domain boundaries or isolate persistence, not automatically for every DbSet.

Code example

public interface IProductRepository { Task<Product?> GetAsync(int id, CancellationToken ct); }

Diagram

Explain repository abstraction → implementation → result

Key Points

  • Avoid generic repositories that hide useful EF Core query capabilities.
Q82Coordinate persistence changes

What is the Unit of Work pattern?

A Unit of Work coordinates changes and commits them together. EF Core DbContext tracks changes and SaveChanges normally acts as the unit-of-work commit bou

Answer

A Unit of Work coordinates changes and commits them together. EF Core DbContext tracks changes and SaveChanges normally acts as the unit-of-work commit boundary.

A single SaveChanges call usually wraps its commands in a transaction when supported by the provider.

Syntax

db.Products.Add(product);
db.AuditEntries.Add(entry);
await db.SaveChangesAsync(ct);

Example

A single SaveChanges call usually wraps its commands in a transaction when supported by the provider.

Code example

db.Products.Add(product);
db.AuditEntries.Add(entry);
await db.SaveChangesAsync(ct);

Diagram

Coordinate persistence changes → implementation → result

Key Points

  • External systems such as email are not automatically included in the database transaction.
Q83Explain ACID transactions

What is a database transaction?

A transaction groups operations into an all-or-nothing unit. ACID refers to atomicity, consistency, isolation, and durability.

Answer

A transaction groups operations into an all-or-nothing unit. ACID refers to atomicity, consistency, isolation, and durability.

Keep transactions short and handle rollback/disposal correctly.

Syntax

await using var tx = await db.Database.BeginTransactionAsync(ct);
// perform operations
await db.SaveChangesAsync(ct);
await tx.CommitAsync(ct);

Example

Keep transactions short and handle rollback/disposal correctly.

Code example

await using var tx = await db.Database.BeginTransactionAsync(ct);
// perform operations
await db.SaveChangesAsync(ct);
await tx.CommitAsync(ct);

Diagram

Explain ACID transactions → implementation → result

Key Points

  • A transaction cannot by itself make a distributed database and external API call atomic.
Q84Prevent lost updates

How do you handle concurrency in EF Core?

Optimistic concurrency detects when a row changed since it was read, often using a rowversion or concurrency token. SaveChanges can throw DbUpdateConcurren

Answer

Optimistic concurrency detects when a row changed since it was read, often using a rowversion or concurrency token. SaveChanges can throw DbUpdateConcurrencyException.

Catch concurrency exceptions and choose a policy: reload, merge, reject, or retry safely.

Syntax

public class Product { public int Id { get; set; } [Timestamp] public byte[] RowVersion { get; set; } = []; }

Example

Catch concurrency exceptions and choose a policy: reload, merge, reject, or retry safely.

Code example

public class Product { public int Id { get; set; } [Timestamp] public byte[] RowVersion { get; set; } = []; }

Diagram

Prevent lost updates → implementation → result

Key Points

  • A retry must re-evaluate business rules using fresh data.
Q85Explain indexes and query performance

What is a database index?

An index helps the database locate rows without scanning the entire table, but it consumes storage and adds write overhead. Index columns should reflect ac

Answer

An index helps the database locate rows without scanning the entire table, but it consumes storage and adds write overhead. Index columns should reflect actual query patterns.

Inspect execution plans and query metrics before adding indexes.

Syntax

modelBuilder.Entity<Product>().HasIndex(p => p.Sku).IsUnique();

Example

Inspect execution plans and query metrics before adding indexes.

Code example

modelBuilder.Entity<Product>().HasIndex(p => p.Sku).IsUnique();

Diagram

Explain indexes and query performance → implementation → result

Key Points

  • Composite index column order affects which query predicates can use it efficiently.
Q86Page API results safely

What is pagination and how do you implement it?

Pagination limits response size. Offset pagination is simple; keyset pagination is often more efficient for large or frequently changing datasets.

Answer

Pagination limits response size. Offset pagination is simple; keyset pagination is often more efficient for large or frequently changing datasets.

Validate page and pageSize, cap maximum page size, and use deterministic ordering.

Syntax

var items = await db.Products.OrderBy(p => p.Id).Skip((page-1)*pageSize).Take(pageSize).ToListAsync(ct);

Example

Validate page and pageSize, cap maximum page size, and use deterministic ordering.

Code example

var items = await db.Products.OrderBy(p => p.Id).Skip((page-1)*pageSize).Take(pageSize).ToListAsync(ct);

Diagram

Page API results safely → implementation → result

Key Points

  • For large datasets, consider a cursor based on the last ordered key.
Q87Compare memory and distributed cache

What is caching in ASP.NET Core?

Caching stores reusable data to reduce latency or backend load. IMemoryCache is local to one process; distributed caches such as Redis can be shared across

Answer

Caching stores reusable data to reduce latency or backend load. IMemoryCache is local to one process; distributed caches such as Redis can be shared across instances.

Choose expiration and invalidation deliberately; avoid caching user-specific data under shared keys.

Syntax

builder.Services.AddMemoryCache();
cache.Set("product:42", product, TimeSpan.FromMinutes(5));

Example

Choose expiration and invalidation deliberately; avoid caching user-specific data under shared keys.

Code example

builder.Services.AddMemoryCache();
cache.Set("product:42", product, TimeSpan.FromMinutes(5));

Diagram

Compare memory and distributed cache → implementation → result

Key Points

  • A cache is not the source of truth and may be stale.
Q88Cache HTTP responses

What is output caching?

Output caching stores generated responses according to configured policies. It is useful for responses that can safely be reused across requests.

Answer

Output caching stores generated responses according to configured policies. It is useful for responses that can safely be reused across requests.

Apply policies only to cacheable endpoints and account for authorization, vary-by parameters, and invalidation.

Syntax

builder.Services.AddOutputCache();
app.UseOutputCache();

Example

Apply policies only to cacheable endpoints and account for authorization, vary-by parameters, and invalidation.

Code example

builder.Services.AddOutputCache();
app.UseOutputCache();

Diagram

Cache HTTP responses → implementation → result

Key Points

  • Do not cache sensitive personalized responses publicly.
Q89Use structured logging

What is logging with ILogger<T>?

ILogger provides category-based structured logging with levels such as Trace, Debug, Information, Warning, Error, and Critical. Structured properties are e

Answer

ILogger provides category-based structured logging with levels such as Trace, Debug, Information, Warning, Error, and Critical. Structured properties are easier to query than concatenated strings.

Use scopes or correlation IDs to connect events across a request.

Syntax

logger.LogInformation("Created product {ProductId}", product.Id);

Example

Use scopes or correlation IDs to connect events across a request.

Code example

logger.LogInformation("Created product {ProductId}", product.Id);

Diagram

Use structured logging → implementation → result

Key Points

  • Never log passwords, access tokens, or sensitive personal data.
Q90Expose application health

What is health checking?

Health checks report whether an app or its dependencies are healthy. Liveness asks whether the process should keep running; readiness asks whether it can a

Answer

Health checks report whether an app or its dependencies are healthy. Liveness asks whether the process should keep running; readiness asks whether it can accept traffic.

Keep liveness checks lightweight; readiness may include critical dependencies.

Syntax

builder.Services.AddHealthChecks();
app.MapHealthChecks("/health");

Example

Keep liveness checks lightweight; readiness may include critical dependencies.

Code example

builder.Services.AddHealthChecks();
app.MapHealthChecks("/health");

Diagram

Expose application health → implementation → result

Key Points

  • Secure detailed health endpoints where they expose internal information.
Q91Document an API contract

What is Swagger/OpenAPI?

OpenAPI describes endpoints, parameters, request/response schemas, and security requirements. Swagger UI can render an interactive documentation page from

Answer

OpenAPI describes endpoints, parameters, request/response schemas, and security requirements. Swagger UI can render an interactive documentation page from an OpenAPI document.

Use DTOs and response metadata to improve generated docs; consider disabling public interactive docs in production.

Syntax

// Register and map OpenAPI/Swagger services according to the target .NET version.

Example

Use DTOs and response metadata to improve generated docs; consider disabling public interactive docs in production.

Code example

// Register and map OpenAPI/Swagger services according to the target .NET version.

Diagram

Document an API contract → implementation → result

Key Points

  • OpenAPI documents a contract
  • it does not guarantee implementation correctness.
Q92Create endpoints with minimal APIs

What is minimal API in ASP.NET Core?

Minimal APIs define HTTP endpoints with less ceremony than controller classes and support DI, filters, binding, and typed results.

Answer

Minimal APIs define HTTP endpoints with less ceremony than controller classes and support DI, filters, binding, and typed results.

Use route groups and endpoint filters to organize larger APIs.

Syntax

var app = builder.Build();
app.MapGet("/api/ping", () => Results.Ok(new { status = "ok" }));
app.Run();

Example

Use route groups and endpoint filters to organize larger APIs.

Code example

var app = builder.Build();
app.MapGet("/api/ping", () => Results.Ok(new { status = "ok" }));
app.Run();

Diagram

Create endpoints with minimal APIs → implementation → result

Key Points

  • Minimal APIs and controllers can coexist in one application.
Q93Explain action and authorization filters

What is a filter in ASP.NET Core MVC?

Filters run at defined stages around MVC request processing. Common kinds include authorization, resource, action, exception, and result filters.

Answer

Filters run at defined stages around MVC request processing. Common kinds include authorization, resource, action, exception, and result filters.

Use middleware for broad HTTP concerns and filters for MVC/action-specific behavior.

Syntax

public sealed class TimingFilter : IAsyncActionFilter { /* measure and call next */ }

Example

Use middleware for broad HTTP concerns and filters for MVC/action-specific behavior.

Code example

public sealed class TimingFilter : IAsyncActionFilter { /* measure and call next */ }

Diagram

Explain action and authorization filters → implementation → result

Key Points

  • Filter order affects behavior
  • prefer built-in features when available.
Q94Choose the right pipeline extension

What is the difference between middleware and filters?

Middleware operates in the HTTP pipeline and can apply to all requests. MVC filters run inside the MVC action-invocation pipeline and have access to action

Answer

Middleware operates in the HTTP pipeline and can apply to all requests. MVC filters run inside the MVC action-invocation pipeline and have access to action context and model state.

Use middleware for correlation, exception handling, and general request processing; filters for MVC-specific concerns.

Syntax

app.Use(async (ctx, next) => await next());

Example

Use middleware for correlation, exception handling, and general request processing; filters for MVC-specific concerns.

Code example

app.Use(async (ctx, next) => await next());

Diagram

Choose the right pipeline extension → implementation → result

Key Points

  • Endpoint filters are also available for minimal APIs.
Q95Map between DTOs and entities

What is AutoMapper and when should you use it?

Object mappers reduce repetitive property-copying code, but mapping rules can hide behavior if overused. Explicit mapping is often clearer for small or sec

Answer

Object mappers reduce repetitive property-copying code, but mapping rules can hide behavior if overused. Explicit mapping is often clearer for small or security-sensitive DTOs.

Use mapping configuration tests and avoid mapping untrusted request objects onto tracked entities blindly.

Syntax

var dto = new ProductDto(entity.Id, entity.Name, entity.Price);

Example

Use mapping configuration tests and avoid mapping untrusted request objects onto tracked entities blindly.

Code example

var dto = new ProductDto(entity.Id, entity.Name, entity.Price);

Diagram

Map between DTOs and entities → implementation → result

Key Points

  • Mapping is not validation or authorization.
Q127C#

How does pattern matching simplify conditional logic?

Pattern matching checks an input against type, constant, relational, property, or list patterns. It can make branching more expressive and reduce

Answer

Pattern matching checks an input against type, constant, relational, property, or list patterns. It can make branching more expressive and reduce unsafe casts.

Apply the approach according to the application's constraints and verify important behavior with automated tests.

Syntax

value switch { int n when n > 0 => "positive", int => "non-positive", _ => "not an integer" }

Example

object value = 12; var label = value switch { int n when n > 0 => "positive", int => "non-positive", _ => "not an integer" };

Code example

object value = 12;\nvar label = value switch\n{\n    int n when n > 0 => "positive",\n    int => "non-positive",\n    _ => "not an integer"\n};

Diagram

Input → pattern checks → first matching arm → result.

Key Points

  • Pattern matching checks an input against type, constant, relational, property, or list patterns.
  • Keep dependencies and responsibilities explicit.
  • Cover error handling and edge cases in tests.
Q129C#

How do you dispose asynchronous resources?

Use await using with IAsyncDisposable when cleanup itself requires asynchronous work, such as flushing or closing an asynchronous resource.

Answer

Use await using with IAsyncDisposable when cleanup itself requires asynchronous work, such as flushing or closing an asynchronous resource.

Apply the approach according to the application's constraints and verify important behavior with automated tests.

Syntax

await using var resource = new AsyncResource();

Example

await using var stream = new FileStream( "data.bin", FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true); // use stream; disposal is awaited

Code example

await using var stream = new FileStream(\n    "data.bin", FileMode.Open, FileAccess.Read, FileShare.Read,\n    bufferSize: 4096, useAsync: true);\n// use stream; disposal is awaited

Diagram

Acquire async resource → perform work → await DisposeAsync during scope exit.

Key Points

  • Use await using with IAsyncDisposable when cleanup itself requires asynchronous work, such as flushing or closing an asynchronous resource.
  • Keep dependencies and responsibilities explicit.
  • Cover error handling and edge cases in tests.
Q131OOP

Explain the Liskov Substitution Principle with a practical example.

A subtype should be usable wherever its base abstraction is expected without breaking correctness or documented expectations. Prefer capability-f

Answer

A subtype should be usable wherever its base abstraction is expected without breaking correctness or documented expectations. Prefer capability-focused interfaces when not every subtype supports every operation.

Apply the approach according to the application's constraints and verify important behavior with automated tests.

Syntax

IReadOnlyCollection<T> exposes reading without requiring mutation.

Example

public interface IReadOnlyShape { double Area(); } public sealed class Circle(double radius) : IReadOnlyShape { public double Area() => Math.PI * radius * radius; }

Code example

public interface IReadOnlyShape { double Area(); }\npublic sealed class Circle(double radius) : IReadOnlyShape\n{ public double Area() => Math.PI * radius * radius; }

Diagram

Client → abstraction contract → any implementation that preserves the contract.

Key Points

  • A subtype should be usable wherever its base abstraction is expected without breaking correctness or documented expectations.
  • Keep dependencies and responsibilities explicit.
  • Cover error handling and edge cases in tests.
Q132OOP

How does the Interface Segregation Principle improve design?

Clients should not depend on methods they do not use. Split large interfaces into cohesive capabilities so implementations only take dependencies

Answer

Clients should not depend on methods they do not use. Split large interfaces into cohesive capabilities so implementations only take dependencies on relevant contracts.

Apply the approach according to the application's constraints and verify important behavior with automated tests.

Syntax

IPrinter.Print(); IScanner.Scan();

Example

public interface IPrinter { void Print(string text); } public interface IScanner { byte[] Scan(); }

Code example

public interface IPrinter { void Print(string text); }\npublic interface IScanner { byte[] Scan(); }

Diagram

Multifunction device → small capability interfaces → focused clients.

Key Points

  • Clients should not depend on methods they do not use.
  • Keep dependencies and responsibilities explicit.
  • Cover error handling and edge cases in tests.
Q133OOP

What is the Dependency Inversion Principle?

High-level policy should depend on abstractions rather than concrete low-level details. Both sides depend on a stable contract, with dependency i

Answer

High-level policy should depend on abstractions rather than concrete low-level details. Both sides depend on a stable contract, with dependency injection supplying the implementation.

Apply the approach according to the application's constraints and verify important behavior with automated tests.

Syntax

OrderService(IOrderRepository repository)

Example

public sealed class OrderService(IOrderRepository repository) { public Task SaveAsync(Order order) => repository.SaveAsync(order); }

Code example

public sealed class OrderService(IOrderRepository repository)\n{\n    public Task SaveAsync(Order order) => repository.SaveAsync(order);\n}

Diagram

OrderService → IOrderRepository ← SqlOrderRepository.

Key Points

  • High-level policy should depend on abstractions rather than concrete low-level details.
  • Keep dependencies and responsibilities explicit.
  • Cover error handling and edge cases in tests.
Q134ASP.NET Core

Why does middleware order matter in ASP.NET Core?

Middleware executes in registration order on the request path and unwinds in reverse on the response path. Authentication must run before authori

Answer

Middleware executes in registration order on the request path and unwinds in reverse on the response path. Authentication must run before authorization, and endpoint mapping should fit the intended pipeline.

Apply the approach according to the application's constraints and verify important behavior with automated tests.

Syntax

app.UseAuthentication(); app.UseAuthorization();

Example

app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllers();

Code example

app.UseRouting();\napp.UseAuthentication();\napp.UseAuthorization();\napp.MapControllers();

Diagram

Request → routing → authentication → authorization → endpoint → response.

Key Points

  • Middleware executes in registration order on the request path and unwinds in reverse on the response path.
  • Keep dependencies and responsibilities explicit.
  • Cover error handling and edge cases in tests.
Q135ASP.NET Core

How do you validate strongly typed configuration with the options pattern?

Bind configuration to a typed options class and validate it during startup. This surfaces invalid configuration early instead of failing during a

Answer

Bind configuration to a typed options class and validate it during startup. This surfaces invalid configuration early instead of failing during a user request.

Apply the approach according to the application's constraints and verify important behavior with automated tests.

Syntax

services.AddOptions<MailOptions>().BindConfiguration("Mail").ValidateOnStart();

Example

builder.Services.AddOptions<MailOptions>() .BindConfiguration("Mail") .Validate(o => o.Port is > 0 and <= 65535, "Invalid port") .ValidateOnStart();

Code example

builder.Services.AddOptions<MailOptions>()\n    .BindConfiguration("Mail")\n    .Validate(o => o.Port is > 0 and <= 65535, "Invalid port")\n    .ValidateOnStart();

Diagram

appsettings → configuration binding → validation → typed options injected into service.

Key Points

  • Bind configuration to a typed options class and validate it during startup.
  • Keep dependencies and responsibilities explicit.
  • Cover error handling and edge cases in tests.
Q136Web API

What is Problem Details in an HTTP API?

Problem Details provides a consistent machine-readable error body with fields such as type, title, status, detail, and instance. Avoid leaking st

Answer

Problem Details provides a consistent machine-readable error body with fields such as type, title, status, detail, and instance. Avoid leaking stack traces or secrets to clients.

Apply the approach according to the application's constraints and verify important behavior with automated tests.

Syntax

HTTP 400 + application/problem+json

Example

return Results.Problem( title: "Invalid request", detail: "The supplied page size is outside the allowed range.", statusCode: StatusCodes.Status400BadRequest);

Code example

return Results.Problem(\n    title: "Invalid request",\n    detail: "The supplied page size is outside the allowed range.",\n    statusCode: StatusCodes.Status400BadRequest);

Diagram

Request fails → exception/validation handler → normalized Problem Details response.

Key Points

  • Problem Details provides a consistent machine-readable error body with fields such as type, title, status, detail, and instance.
  • Keep dependencies and responsibilities explicit.
  • Cover error handling and edge cases in tests.
Q139Dependency Injection

What are keyed services in modern .NET dependency injection?

Keyed services register multiple implementations under distinct keys. Resolve the implementation by key when the choice is explicit and stable; a

Answer

Keyed services register multiple implementations under distinct keys. Resolve the implementation by key when the choice is explicit and stable; avoid turning service location into a general-purpose pattern.

Apply the approach according to the application's constraints and verify important behavior with automated tests.

Syntax

services.AddKeyedScoped<INotifier, EmailNotifier>("email");

Example

builder.Services.AddKeyedScoped<INotifier, EmailNotifier>("email"); builder.Services.AddKeyedScoped<INotifier, SmsNotifier>("sms"); // Inject with [FromKeyedServices("email")] INotifier notifier

Code example

builder.Services.AddKeyedScoped<INotifier, EmailNotifier>("email");\nbuilder.Services.AddKeyedScoped<INotifier, SmsNotifier>("sms");\n// Inject with [FromKeyedServices("email")] INotifier notifier

Diagram

Registration key → DI container → matching implementation.

Key Points

  • Keyed services register multiple implementations under distinct keys.
  • Keep dependencies and responsibilities explicit.
  • Cover error handling and edge cases in tests.
Q141Asynchronous Programming

How should CancellationToken be propagated through async methods?

Accept a CancellationToken, pass it to cancellable downstream APIs, and honor cancellation rather than swallowing OperationCanceledException indi

Answer

Accept a CancellationToken, pass it to cancellable downstream APIs, and honor cancellation rather than swallowing OperationCanceledException indiscriminately. Cancellation is cooperative.

Apply the approach according to the application's constraints and verify important behavior with automated tests.

Syntax

Task<T> GetAsync(CancellationToken cancellationToken)

Example

public async Task<string> ReadAsync(CancellationToken cancellationToken) { using var response = await client.GetAsync("/data", cancellationToken); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync(cancellationToken); }

Code example

public async Task<string> ReadAsync(CancellationToken cancellationToken)\n{\n    using var response = await client.GetAsync("/data", cancellationToken);\n    response.EnsureSuccessStatusCode();\n    return await response.Content.ReadAsStringAsync(cancellationToken);\n}

Diagram

HTTP request cancelled → token propagated → downstream operation stops cooperatively.

Key Points

  • Accept a CancellationToken, pass it to cancellable downstream APIs, and honor cancellation rather than swallowing OperationCanceledException indiscriminately.
  • Keep dependencies and responsibilities explicit.
  • Cover error handling and edge cases in tests.
Q142Asynchronous Programming

When should you use Task.WhenAll?

Task.WhenAll waits for multiple tasks and enables independent I/O operations to overlap. It does not create threads by itself, and concurrency sh

Answer

Task.WhenAll waits for multiple tasks and enables independent I/O operations to overlap. It does not create threads by itself, and concurrency should be bounded when many operations are launched.

Apply the approach according to the application's constraints and verify important behavior with automated tests.

Syntax

await Task.WhenAll(taskA, taskB);

Example

Task<User> userTask = GetUserAsync(id, ct); Task<IReadOnlyList<Order>> ordersTask = GetOrdersAsync(id, ct); await Task.WhenAll(userTask, ordersTask); var result = (await userTask, await ordersTask);

Code example

Task<User> userTask = GetUserAsync(id, ct);\nTask<IReadOnlyList<Order>> ordersTask = GetOrdersAsync(id, ct);\nawait Task.WhenAll(userTask, ordersTask);\nvar result = (await userTask, await ordersTask);

Diagram

Start independent I/O tasks → await all → combine results.

Key Points

  • Task.
  • Keep dependencies and responsibilities explicit.
  • Cover error handling and edge cases in tests.
Q145Design Patterns

How does the Strategy pattern help select business rules?

Strategy encapsulates interchangeable algorithms behind a common interface. The caller depends on the abstraction and can select a policy through

Answer

Strategy encapsulates interchangeable algorithms behind a common interface. The caller depends on the abstraction and can select a policy through configuration or DI.

Apply the approach according to the application's constraints and verify important behavior with automated tests.

Syntax

IDiscountStrategy.Calculate(order)

Example

public interface IDiscountStrategy { decimal Calculate(decimal total); } public sealed class VipDiscount : IDiscountStrategy { public decimal Calculate(decimal total) => total * 0.9m; }

Code example

public interface IDiscountStrategy { decimal Calculate(decimal total); }\npublic sealed class VipDiscount : IDiscountStrategy\n{ public decimal Calculate(decimal total) => total * 0.9m; }

Diagram

Checkout → IDiscountStrategy → selected discount strategy.

Key Points

  • Strategy encapsulates interchangeable algorithms behind a common interface.
  • Keep dependencies and responsibilities explicit.
  • Cover error handling and edge cases in tests.
Q146Design Patterns

What is the Decorator pattern and where is it useful?

Decorator wraps an object implementing the same abstraction to add behavior without modifying the wrapped implementation. Common uses include log

Answer

Decorator wraps an object implementing the same abstraction to add behavior without modifying the wrapped implementation. Common uses include logging, caching, metrics, and retries.

Apply the approach according to the application's constraints and verify important behavior with automated tests.

Syntax

new LoggingRepository(new SqlRepository())

Example

public sealed class LoggingRepository(IRepository inner, ILogger<LoggingRepository> log) : IRepository { public async Task SaveAsync(Item item) { log.LogInformation("Saving item"); await inner.SaveAsync(item); } }

Code example

public sealed class LoggingRepository(IRepository inner, ILogger<LoggingRepository> log) : IRepository\n{\n    public async Task SaveAsync(Item item)\n    { log.LogInformation("Saving item"); await inner.SaveAsync(item); }\n}

Diagram

Caller → decorator (logging) → underlying repository.

Key Points

  • Decorator wraps an object implementing the same abstraction to add behavior without modifying the wrapped implementation.
  • Keep dependencies and responsibilities explicit.
  • Cover error handling and edge cases in tests.
Q147Design Patterns

When is the Factory pattern useful in a .NET application?

A factory centralizes creation when construction is conditional, complex, or depends on runtime input. For simple services, built-in DI registrat

Answer

A factory centralizes creation when construction is conditional, complex, or depends on runtime input. For simple services, built-in DI registration is often enough and a custom factory may be unnecessary.

Apply the approach according to the application's constraints and verify important behavior with automated tests.

Syntax

IParser parser = parserFactory.Create(format);

Example

public IParser Create(string format) => format switch { "json" => new JsonParser(), "xml" => new XmlParser(), _ => throw new NotSupportedException(format) };

Code example

public IParser Create(string format) => format switch\n{\n    "json" => new JsonParser(),\n    "xml" => new XmlParser(),\n    _ => throw new NotSupportedException(format)\n};

Diagram

Format input → factory selection → matching parser instance.

Key Points

  • A factory centralizes creation when construction is conditional, complex, or depends on runtime input.
  • Keep dependencies and responsibilities explicit.
  • Cover error handling and edge cases in tests.
Q150ASP.NET Core

How do readiness and liveness health checks differ?

Liveness indicates whether the process should be restarted; readiness indicates whether it can safely receive traffic. Avoid making liveness depe

Answer

Liveness indicates whether the process should be restarted; readiness indicates whether it can safely receive traffic. Avoid making liveness depend on remote systems, which can cause restart cascades.

Apply the approach according to the application's constraints and verify important behavior with automated tests.

Syntax

MapHealthChecks("/health/ready")

Example

builder.Services.AddHealthChecks(); app.MapHealthChecks("/health/live"); app.MapHealthChecks("/health/ready");

Code example

builder.Services.AddHealthChecks();\napp.MapHealthChecks("/health/live");\napp.MapHealthChecks("/health/ready");

Diagram

Orchestrator checks liveness for restart decisions and readiness for traffic routing.

Key Points

  • Liveness indicates whether the process should be restarted; readiness indicates whether it can safely receive traffic.
  • Keep dependencies and responsibilities explicit.
  • Cover error handling and edge cases in tests.

Advanced Questions

Architecture, optimization, and design trade-offs.

Q96Trace an HTTP request

Explain the ASP.NET Core request pipeline end-to-end.

A request enters the web server, passes through middleware, routing, authentication/authorization and endpoint execution, then the response unwinds through

Answer

A request enters the web server, passes through middleware, routing, authentication/authorization and endpoint execution, then the response unwinds through middleware. Exact ordering depends on configuration.

Place exception handling early; route before endpoint-specific authorization as required by the hosting model.

Diagram / flow: Client → Kestrel/reverse proxy → middleware → routing → authn/authz → endpoint → response

Syntax

Client → Kestrel/reverse proxy → middleware → routing → authn/authz → endpoint → response

Example

Place exception handling early; route before endpoint-specific authorization as required by the hosting model.

Code example

Client → Kestrel/reverse proxy → middleware → routing → authn/authz → endpoint → response

Diagram

Diagram / flow:
Client → Kestrel/reverse proxy → middleware → routing → authn/authz → endpoint → response

Key Points

  • Use logs and tracing to diagnose where a request was short-circuited.
Q97Separate domain, application, infrastructure, and presentation

How do you design a clean architecture solution?

Clean Architecture keeps domain rules independent of infrastructure frameworks. Application use cases coordinate domain behavior; infrastructure implements

Answer

Clean Architecture keeps domain rules independent of infrastructure frameworks. Application use cases coordinate domain behavior; infrastructure implements persistence and external services; the API is an entry point.

Keep EF Core, HTTP, and provider-specific details at the outer boundary where practical.

Diagram / flow: API → Application → Domain Infrastructure implements Application abstractions Dependency direction points inward.

Syntax

API → Application → Domain
Infrastructure implements Application abstractions
Dependency direction points inward.

Example

Keep EF Core, HTTP, and provider-specific details at the outer boundary where practical.

Code example

API → Application → Domain
Infrastructure implements Application abstractions
Dependency direction points inward.

Diagram

Diagram / flow:
API → Application → Domain
Infrastructure implements Application abstractions
Dependency direction points inward.

Key Points

  • Avoid adding layers without clear ownership or a useful dependency boundary.
Q98Separate command and query models

What is CQRS?

CQRS separates operations that change state (commands) from operations that read state (queries). It can clarify models and scale needs but adds complexity

Answer

CQRS separates operations that change state (commands) from operations that read state (queries). It can clarify models and scale needs but adds complexity.

Start with a simple service architecture; introduce separate read models when requirements justify them.

Diagram / flow: POST /orders → command handler GET /orders/{id} → query handler

Syntax

POST /orders → command handler
GET /orders/{id} → query handler

Example

Start with a simple service architecture; introduce separate read models when requirements justify them.

Code example

POST /orders → command handler
GET /orders/{id} → query handler

Diagram

Diagram / flow:
POST /orders → command handler
GET /orders/{id} → query handler

Key Points

  • CQRS does not require event sourcing or separate databases.
Q99Use mediator-style request handling

What is MediatR and when is it useful?

A mediator dispatches a request to a handler, reducing direct coupling between callers and handlers. It can organize use cases, but pipeline behaviors and

Answer

A mediator dispatches a request to a handler, reducing direct coupling between callers and handlers. It can organize use cases, but pipeline behaviors and indirection have a cost.

Use handlers for cohesive use cases and shared behaviors such as validation or metrics.

Syntax

public record GetProductQuery(int Id) : IRequest<ProductDto?>;

Example

Use handlers for cohesive use cases and shared behaviors such as validation or metrics.

Code example

public record GetProductQuery(int Id) : IRequest<ProductDto?>;

Diagram

Use mediator-style request handling → implementation → result

Key Points

  • A mediator is not a replacement for good module boundaries.
Q100Explain DDD building blocks

What is domain-driven design?

DDD models complex business domains using a shared language, entities, value objects, aggregates, repositories, and domain services. It is most valuable wh

Answer

DDD models complex business domains using a shared language, entities, value objects, aggregates, repositories, and domain services. It is most valuable when business rules are complex.

Keep aggregate boundaries aligned with invariants and transaction needs.

Diagram / flow: Order aggregate → OrderLine entities/value objects → invariant-preserving methods

Syntax

Order aggregate → OrderLine entities/value objects → invariant-preserving methods

Example

Keep aggregate boundaries aligned with invariants and transaction needs.

Code example

Order aggregate → OrderLine entities/value objects → invariant-preserving methods

Diagram

Diagram / flow:
Order aggregate → OrderLine entities/value objects → invariant-preserving methods

Key Points

  • Do not force DDD ceremony onto simple CRUD applications.
Q101Protect domain invariants

What is an aggregate root?

An aggregate root is the entry point for changing an aggregate and protects its invariants. External code should not arbitrarily modify internal entities i

Answer

An aggregate root is the entry point for changing an aggregate and protects its invariants. External code should not arbitrarily modify internal entities in ways that bypass rules.

Expose intent-revealing methods rather than public setters for invariant-sensitive state.

Syntax

order.AddLine(productId, quantity);

Example

Expose intent-revealing methods rather than public setters for invariant-sensitive state.

Code example

order.AddLine(productId, quantity);

Diagram

Protect domain invariants → implementation → result

Key Points

  • Aggregate boundaries influence consistency and transaction scope.
Q102Store state changes as events

What is event sourcing?

Event sourcing stores a sequence of domain events as the primary record and derives current state by replaying them. It supports audit/history but complica

Answer

Event sourcing stores a sequence of domain events as the primary record and derives current state by replaying them. It supports audit/history but complicates projections, schema evolution, and operations.

Use snapshots or projections when replay becomes expensive.

Diagram / flow: OrderPlaced → ItemAdded → PaymentCaptured → OrderShipped

Syntax

OrderPlaced → ItemAdded → PaymentCaptured → OrderShipped

Example

Use snapshots or projections when replay becomes expensive.

Code example

OrderPlaced → ItemAdded → PaymentCaptured → OrderShipped

Diagram

Diagram / flow:
OrderPlaced → ItemAdded → PaymentCaptured → OrderShipped

Key Points

  • Event sourcing is distinct from ordinary application logging.
Q103Publish events reliably with database changes

What is the transactional outbox pattern?

The outbox writes the business change and an outgoing message record in the same database transaction. A background publisher later sends messages and mark

Answer

The outbox writes the business change and an outgoing message record in the same database transaction. A background publisher later sends messages and marks them processed.

Consumers should be idempotent because publishing may happen more than once.

Diagram / flow: Transaction: update Order + insert OutboxMessage Worker → broker → mark sent

Syntax

Transaction: update Order + insert OutboxMessage
Worker → broker → mark sent

Example

Consumers should be idempotent because publishing may happen more than once.

Code example

Transaction: update Order + insert OutboxMessage
Worker → broker → mark sent

Diagram

Diagram / flow:
Transaction: update Order + insert OutboxMessage
Worker → broker → mark sent

Key Points

  • The pattern closes the database/broker dual-write gap
  • it does not provide magical exactly-once delivery.
Q104Handle safe retries

How do you implement idempotency for a POST endpoint?

Accept an idempotency key, associate it with the caller and request, persist the result or operation state atomically, and return the same outcome for dupl

Answer

Accept an idempotency key, associate it with the caller and request, persist the result or operation state atomically, and return the same outcome for duplicate requests.

Define key retention, payload mismatch behavior, and concurrent duplicate handling.

Syntax

Unique key: (TenantId, IdempotencyKey)
POST /payments + Idempotency-Key: abc123

Example

Define key retention, payload mismatch behavior, and concurrent duplicate handling.

Code example

Unique key: (TenantId, IdempotencyKey)
POST /payments + Idempotency-Key: abc123

Diagram

Handle safe retries → implementation → result

Key Points

  • A client-generated key alone is insufficient without durable server-side coordination.
Q105Keep stock updates consistent

How do you prevent race conditions during inventory updates?

Use a database constraint and atomic conditional update, or optimistic/pessimistic concurrency according to requirements. Do not read stock and later write

Answer

Use a database constraint and atomic conditional update, or optimistic/pessimistic concurrency according to requirements. Do not read stock and later write a new value without guarding against competing requests.

Check affected row count; zero rows means insufficient stock or a missing product.

Syntax

UPDATE Products SET Stock = Stock - @qty WHERE Id = @id AND Stock >= @qty

Example

Check affected row count; zero rows means insufficient stock or a missing product.

Code example

UPDATE Products SET Stock = Stock - @qty WHERE Id = @id AND Stock >= @qty

Diagram

Keep stock updates consistent → implementation → result

Key Points

  • Keep the invariant in the database transaction boundary, not only in UI validation.
Q106Protect APIs from excess traffic

How do you implement rate limiting in ASP.NET Core?

ASP.NET Core provides rate-limiting middleware with fixed-window, sliding-window, token-bucket, and concurrency limiters depending on target version. Parti

Answer

ASP.NET Core provides rate-limiting middleware with fixed-window, sliding-window, token-bucket, and concurrency limiters depending on target version. Partition limits by a meaningful identity where appropriate.

Return 429 and consider Retry-After; configure trusted proxy/client identity handling carefully.

Syntax

builder.Services.AddRateLimiter(o => o.AddFixedWindowLimiter("api", opt => { opt.PermitLimit = 100; opt.Window = TimeSpan.FromMinutes(1); }));
app.UseRateLimiter();

Example

Return 429 and consider Retry-After; configure trusted proxy/client identity handling carefully.

Code example

builder.Services.AddRateLimiter(o => o.AddFixedWindowLimiter("api", opt => { opt.PermitLimit = 100; opt.Window = TimeSpan.FromMinutes(1); }));
app.UseRateLimiter();

Diagram

Protect APIs from excess traffic → implementation → result

Key Points

  • In-memory limits are per process unless a distributed strategy is used.
Q107Keep cached data consistent

How do you handle distributed caching invalidation?

Define cache keys, TTLs, invalidation triggers, and acceptable staleness. Update durable state first and invalidate or refresh affected keys; use versionin

Answer

Define cache keys, TTLs, invalidation triggers, and acceptable staleness. Update durable state first and invalidate or refresh affected keys; use versioning or messaging when multiple services share caches.

Use short TTLs as a safety net and design for missed invalidation messages.

Diagram / flow: Write database → invalidate product:42 → next read reloads

Syntax

Write database → invalidate product:42 → next read reloads

Example

Use short TTLs as a safety net and design for missed invalidation messages.

Code example

Write database → invalidate product:42 → next read reloads

Diagram

Diagram / flow:
Write database → invalidate product:42 → next read reloads

Key Points

  • Cache invalidation is a consistency decision, not just a performance setting.
Q108Prevent cascading failures

What is a circuit breaker?

A circuit breaker temporarily blocks calls to a failing dependency after a threshold, allows a limited recovery probe, and closes when the dependency recov

Answer

A circuit breaker temporarily blocks calls to a failing dependency after a threshold, allows a limited recovery probe, and closes when the dependency recovers.

Combine with timeouts, bounded retries, bulkheads, and fallback only when a safe fallback exists.

Diagram / flow: Caller → circuit breaker → downstream API

Syntax

Caller → circuit breaker → downstream API

Example

Combine with timeouts, bounded retries, bulkheads, and fallback only when a safe fallback exists.

Code example

Caller → circuit breaker → downstream API

Diagram

Diagram / flow:
Caller → circuit breaker → downstream API

Key Points

  • Retries and circuit breakers solve different failure patterns.
Q109Isolate resource pools

What is the bulkhead pattern?

Bulkheads isolate workloads so a slow or failing dependency does not exhaust resources needed by unrelated work. Isolation can use separate concurrency lim

Answer

Bulkheads isolate workloads so a slow or failing dependency does not exhaust resources needed by unrelated work. Isolation can use separate concurrency limits, queues, or pools.

Set bounded concurrency and queue sizes; reject or defer excess work deliberately.

Diagram / flow: Orders pool || Reports pool || Notifications pool

Syntax

Orders pool || Reports pool || Notifications pool

Example

Set bounded concurrency and queue sizes; reject or defer excess work deliberately.

Code example

Orders pool || Reports pool || Notifications pool

Diagram

Diagram / flow:
Orders pool || Reports pool || Notifications pool

Key Points

  • A separate class alone is not a bulkhead.
Q110Find blocked request workers

How do you diagnose thread-pool starvation?

Symptoms can include rising latency, low throughput, and many queued work items. Common causes include sync-over-async, blocking I/O, excessive locks, or u

Answer

Symptoms can include rising latency, low throughput, and many queued work items. Common causes include sync-over-async, blocking I/O, excessive locks, or unbounded CPU work.

Use runtime counters, traces, dumps, and load tests; fix blocking rather than merely increasing thread counts.

Syntax

Avoid: var result = SomeAsync().Result;
Prefer: var result = await SomeAsync();

Example

Use runtime counters, traces, dumps, and load tests; fix blocking rather than merely increasing thread counts.

Code example

Avoid: var result = SomeAsync().Result;
Prefer: var result = await SomeAsync();

Diagram

Find blocked request workers → implementation → result

Key Points

  • Adding threads can mask but not resolve the root cause.
Q111Use async safely

How do you avoid deadlocks in asynchronous code?

Avoid blocking on Task with .Wait() or .Result, keep lock scopes short, never await inside a C# lock, and use SemaphoreSlim when asynchronous mutual exclus

Answer

Avoid blocking on Task with .Wait() or .Result, keep lock scopes short, never await inside a C# lock, and use SemaphoreSlim when asynchronous mutual exclusion is needed.

Cancellation and finally blocks are essential when acquiring async locks.

Syntax

await _semaphore.WaitAsync(ct);
try { await WorkAsync(ct); }
finally { _semaphore.Release(); }

Example

Cancellation and finally blocks are essential when acquiring async locks.

Code example

await _semaphore.WaitAsync(ct);
try { await WorkAsync(ct); }
finally { _semaphore.Release(); }

Diagram

Use async safely → implementation → result

Key Points

  • Deadlocks can also occur in databases and distributed workflows, not only task scheduling.
Q112Optimize data access based on evidence

How do you tune EF Core query performance?

Project only needed columns, use no-tracking queries for read-only data, index predicates, avoid N+1 patterns, limit result sets, and inspect generated SQL

Answer

Project only needed columns, use no-tracking queries for read-only data, index predicates, avoid N+1 patterns, limit result sets, and inspect generated SQL and execution plans.

Measure before and after with representative data and query plans.

Syntax

var rows = await db.Products.AsNoTracking().Where(p => p.Active).Select(p => new ProductDto(p.Id, p.Name, p.Price)).ToListAsync(ct);

Example

Measure before and after with representative data and query plans.

Code example

var rows = await db.Products.AsNoTracking().Where(p => p.Active).Select(p => new ProductDto(p.Id, p.Name, p.Price)).ToListAsync(ct);

Diagram

Optimize data access based on evidence → implementation → result

Key Points

  • Compiled queries help specific repeated query workloads but are not the first optimization to try.
Q113Reduce repeated query compilation overhead

What are compiled queries in EF Core?

EF Core compiled queries cache a compiled query delegate for repeated query shapes. They can help hot paths, but normal query caching already handles many

Answer

EF Core compiled queries cache a compiled query delegate for repeated query shapes. They can help hot paths, but normal query caching already handles many scenarios.

Benchmark with production-like workloads before adopting.

Syntax

private static readonly Func<AppDbContext,int,IAsyncEnumerable<Product>> ById = EF.CompileAsyncQuery((AppDbContext db, int id) => db.Products.Where(p => p.Id == id));

Example

Benchmark with production-like workloads before adopting.

Code example

private static readonly Func<AppDbContext,int,IAsyncEnumerable<Product>> ById = EF.CompileAsyncQuery((AppDbContext db, int id) => db.Products.Where(p => p.Id == id));

Diagram

Reduce repeated query compilation overhead → implementation → result

Key Points

  • Compiled queries have constraints and do not fix slow SQL or missing indexes.
Q114Deploy schema changes safely

How do you manage database migrations in production?

Generate and review migration scripts, test against representative data, apply through a controlled deployment identity, and use expand-and-contract change

Answer

Generate and review migration scripts, test against representative data, apply through a controlled deployment identity, and use expand-and-contract changes for rolling deployments.

Avoid having every app instance run migrations concurrently at startup in production.

Diagram / flow: Release A: add nullable column → backfill → Release B: use column → later enforce constraints

Syntax

Release A: add nullable column → backfill → Release B: use column → later enforce constraints

Example

Avoid having every app instance run migrations concurrently at startup in production.

Code example

Release A: add nullable column → backfill → Release B: use column → later enforce constraints

Diagram

Diagram / flow:
Release A: add nullable column → backfill → Release B: use column → later enforce constraints

Key Points

  • Rollback scripts may be unsafe after data has changed
  • plan forward fixes.
Q115Use hosted services safely

How do you implement background jobs in ASP.NET Core?

IHostedService and BackgroundService run hosted work. Use bounded queues or a durable job system for important jobs, create DI scopes for scoped services,

Answer

IHostedService and BackgroundService run hosted work. Use bounded queues or a durable job system for important jobs, create DI scopes for scoped services, and handle cancellation and retries.

Use a durable queue/scheduler when work must survive process restarts or run across replicas.

Syntax

public sealed class Worker(IServiceScopeFactory scopes) : BackgroundService { protected override async Task ExecuteAsync(CancellationToken stoppingToken) { /* loop */ } }

Example

Use a durable queue/scheduler when work must survive process restarts or run across replicas.

Code example

public sealed class Worker(IServiceScopeFactory scopes) : BackgroundService { protected override async Task ExecuteAsync(CancellationToken stoppingToken) { /* loop */ } }

Diagram

Use hosted services safely → implementation → result

Key Points

  • Do not run untracked fire-and-forget tasks from a controller.
Q116Stop accepting work and drain safely

How do you design graceful shutdown?

On shutdown, stop accepting new work, signal cancellation, allow bounded time for in-flight requests/jobs to finish, and release resources. Hosted services

Answer

On shutdown, stop accepting new work, signal cancellation, allow bounded time for in-flight requests/jobs to finish, and release resources. Hosted services should observe their stopping token.

Configure orchestration termination grace periods and readiness behavior consistently.

Syntax

await host.StopAsync(timeoutToken);

Example

Configure orchestration termination grace periods and readiness behavior consistently.

Code example

await host.StopAsync(timeoutToken);

Diagram

Stop accepting work and drain safely → implementation → result

Key Points

  • A forced process kill can still interrupt work, so durable work needs recovery semantics.
Q117Instrument traces, metrics, and logs

What is OpenTelemetry in .NET?

OpenTelemetry provides vendor-neutral instrumentation and export for distributed traces, metrics, and logs. Trace context links work across HTTP and messag

Answer

OpenTelemetry provides vendor-neutral instrumentation and export for distributed traces, metrics, and logs. Trace context links work across HTTP and messaging boundaries.

Use consistent service names, sampling, and redaction of sensitive attributes.

Diagram / flow: builder.Services.AddOpenTelemetry().WithTracing(t => t.AddAspNetCoreInstrumentation().AddHttpClientInstrumentation());

Syntax

builder.Services.AddOpenTelemetry().WithTracing(t => t.AddAspNetCoreInstrumentation().AddHttpClientInstrumentation());

Example

Use consistent service names, sampling, and redaction of sensitive attributes.

Code example

builder.Services.AddOpenTelemetry().WithTracing(t => t.AddAspNetCoreInstrumentation().AddHttpClientInstrumentation());

Diagram

Diagram / flow:
builder.Services.AddOpenTelemetry().WithTracing(t => t.AddAspNetCoreInstrumentation().AddHttpClientInstrumentation());

Key Points

  • Telemetry should be useful and bounded
  • avoid high-cardinality metric labels.
Q118Propagate trace context

How do you correlate logs across microservices?

Use W3C Trace Context-compatible tracing, propagate trace headers through HTTP and messaging, and include trace/span identifiers in logs.

Answer

Use W3C Trace Context-compatible tracing, propagate trace headers through HTTP and messaging, and include trace/span identifiers in logs.

Use OpenTelemetry instrumentation and a collector/backend to view end-to-end traces.

Syntax

Service A --traceparent--> Service B --traceparent--> Service C

Example

Use OpenTelemetry instrumentation and a collector/backend to view end-to-end traces.

Code example

Service A --traceparent--> Service B --traceparent--> Service C

Diagram

Propagate trace context → implementation → result

Key Points

  • Do not trust arbitrary inbound baggage as safe business data.
Q119Manage breaking API changes

How do you version a Web API?

Versioning can use URL segments, query parameters, headers, or media types. Choose a consistent approach, document supported versions, and provide a deprec

Answer

Versioning can use URL segments, query parameters, headers, or media types. Choose a consistent approach, document supported versions, and provide a deprecation path.

Prefer additive compatible changes when possible and test old clients during rollout.

Syntax

/api/v1/products
/api/v2/products

Example

Prefer additive compatible changes when possible and test old clients during rollout.

Code example

/api/v1/products
/api/v2/products

Diagram

Manage breaking API changes → implementation → result

Key Points

  • Versioning does not excuse inconsistent resource semantics.
Q120Build stable keyset pagination

How do you implement API pagination with cursor tokens?

Sort by a unique stable ordering, return the last key as a cursor, and query for rows after that key. Encode and validate cursor data; protect it if it con

Answer

Sort by a unique stable ordering, return the last key as a cursor, and query for rows after that key. Encode and validate cursor data; protect it if it contains sensitive information.

Cursor pagination avoids large offsets and reduces some drift during concurrent inserts.

Syntax

var page = await db.Products.Where(p => p.Id > afterId).OrderBy(p => p.Id).Take(pageSize).ToListAsync(ct);

Example

Cursor pagination avoids large offsets and reduces some drift during concurrent inserts.

Code example

var page = await db.Products.Where(p => p.Id > afterId).OrderBy(p => p.Id).Take(pageSize).ToListAsync(ct);

Diagram

Build stable keyset pagination → implementation → result

Key Points

  • The cursor must match the sort order and include tie-breakers when sort keys are not unique.
Q121Validate and isolate uploaded files

How do you secure file uploads?

Enforce size limits, allowlist file types, inspect content rather than trusting extensions, generate server-side names, store outside executable web roots,

Answer

Enforce size limits, allowlist file types, inspect content rather than trusting extensions, generate server-side names, store outside executable web roots, and scan files where appropriate.

Apply authorization, quotas, malware scanning, and safe download headers.

Syntax

// Validate length + extension + detected content type before persisting.

Example

Apply authorization, quotas, malware scanning, and safe download headers.

Code example

// Validate length + extension + detected content type before persisting.

Diagram

Validate and isolate uploaded files → implementation → result

Key Points

  • Never trust client-provided file names or MIME types.
Q122Bind only permitted fields

How do you prevent mass assignment vulnerabilities?

Mass assignment happens when request fields are copied onto sensitive domain/entity properties without an allowlist. Use dedicated request DTOs and explici

Answer

Mass assignment happens when request fields are copied onto sensitive domain/entity properties without an allowlist. Use dedicated request DTOs and explicitly map allowed fields.

Do not let clients set OwnerId, IsAdmin, payment status, or audit fields unless specifically authorized.

Syntax

var entity = new Product { Name = request.Name, Price = request.Price };

Example

Do not let clients set OwnerId, IsAdmin, payment status, or audit fields unless specifically authorized.

Code example

var entity = new Product { Name = request.Name, Price = request.Price };

Diagram

Bind only permitted fields → implementation → result

Key Points

  • Server-side authorization and domain validation are still required.
Q123Control server-side outbound requests

How do you defend against SSRF?

Server-side request forgery can occur when an API fetches a user-supplied URL. Restrict schemes and destinations, validate DNS/IP results, block private/me

Answer

Server-side request forgery can occur when an API fetches a user-supplied URL. Restrict schemes and destinations, validate DNS/IP results, block private/metadata networks, and use egress controls.

Disable redirects or revalidate each redirect target when appropriate.

Syntax

// Prefer allowlisted destination identifiers over arbitrary URLs.

Example

Disable redirects or revalidate each redirect target when appropriate.

Code example

// Prefer allowlisted destination identifiers over arbitrary URLs.

Diagram

Control server-side outbound requests → implementation → result

Key Points

  • URL validation alone can be bypassed by DNS rebinding or redirect behavior.
Q124Isolate tenant data

How do you implement multi-tenancy?

Identify tenant context from a trusted authenticated claim or validated host, enforce tenant scoping in every query, and consider database-per-tenant or sh

Answer

Identify tenant context from a trusted authenticated claim or validated host, enforce tenant scoping in every query, and consider database-per-tenant or shared-schema isolation based on risk and scale.

Add database constraints and tests that attempt cross-tenant access.

Syntax

Global query filter: e => e.TenantId == currentTenant.Id

Example

Add database constraints and tests that attempt cross-tenant access.

Code example

Global query filter: e => e.TenantId == currentTenant.Id

Diagram

Isolate tenant data → implementation → result

Key Points

  • Never trust a tenant ID supplied only in the request body.
Q125Migrate incrementally

What is the strangler pattern for legacy modernization?

The strangler pattern routes selected capabilities to a new implementation while the legacy system continues serving the rest. Over time, more routes move

Answer

The strangler pattern routes selected capabilities to a new implementation while the legacy system continues serving the rest. Over time, more routes move and legacy scope shrinks.

Choose bounded slices, monitor parity, and maintain a rollback route during migration.

Diagram / flow: Client → routing facade → {legacy system | new .NET API}

Syntax

Client → routing facade → {legacy system | new .NET API}

Example

Choose bounded slices, monitor parity, and maintain a rollback route during migration.

Code example

Client → routing facade → {legacy system | new .NET API}

Diagram

Diagram / flow:
Client → routing facade → {legacy system | new .NET API}

Key Points

  • Avoid a big-bang rewrite unless constraints justify it.
Q128C#

What are Span<T> and Memory<T> used for?

Span<T> represents a contiguous region of memory without copying. It is stack-only and cannot be stored in ordinary heap objects or cross an awai

Answer

Span<T> represents a contiguous region of memory without copying. It is stack-only and cannot be stored in ordinary heap objects or cross an await boundary; Memory<T> supports longer-lived scenarios.

Apply the approach according to the application's constraints and verify important behavior with automated tests.

Syntax

Span<int> slice = values.AsSpan(1, 3);

Example

int[] values = { 10, 20, 30, 40 }; Span<int> slice = values.AsSpan(1, 2); slice[0] = 99; // changes values[1]

Code example

int[] values = { 10, 20, 30, 40 };\nSpan<int> slice = values.AsSpan(1, 2);\nslice[0] = 99; // changes values[1]

Diagram

Array → Span slice → operate on the same memory without allocating a copied array.

Key Points

  • Span<T> represents a contiguous region of memory without copying.
  • Keep dependencies and responsibilities explicit.
  • Cover error handling and edge cases in tests.
Q137Web API

How can an API safely handle retried payment requests?

Use an idempotency key scoped to the caller and operation, persist the request/result atomically, and return the original result for duplicate su

Answer

Use an idempotency key scoped to the caller and operation, persist the request/result atomically, and return the original result for duplicate submissions. Also enforce uniqueness and expiry policies.

Apply the approach according to the application's constraints and verify important behavior with automated tests.

Syntax

Idempotency-Key: 8f1... (unique per logical operation)

Example

if (await store.TryGetResultAsync(key) is { } saved) return saved; var result = await paymentService.ChargeAsync(request); await store.SaveResultAtomicallyAsync(key, result);

Code example

if (await store.TryGetResultAsync(key) is { } saved) return saved;\nvar result = await paymentService.ChargeAsync(request);\nawait store.SaveResultAtomicallyAsync(key, result);

Diagram

Client retry → key lookup → existing result OR execute once and persist result.

Key Points

  • Use an idempotency key scoped to the caller and operation, persist the request/result atomically, and return the original result for duplicate submissions.
  • Keep dependencies and responsibilities explicit.
  • Cover error handling and edge cases in tests.
Q138Web API

How do ETags help prevent lost updates?

An ETag represents a version of a resource. A client sends If-Match when updating; the server rejects the write if the current version no longer

Answer

An ETag represents a version of a resource. A client sends If-Match when updating; the server rejects the write if the current version no longer matches, commonly with 412 Precondition Failed.

Apply the approach according to the application's constraints and verify important behavior with automated tests.

Syntax

PUT /items/42 with If-Match: "v7"

Example

if (request.Headers.IfMatch != currentEtag) return Results.StatusCode(StatusCodes.Status412PreconditionFailed); // apply update and issue a new ETag

Code example

if (request.Headers.IfMatch != currentEtag)\n    return Results.StatusCode(StatusCodes.Status412PreconditionFailed);\n// apply update and issue a new ETag

Diagram

Read version v7 → client sends If-Match v7 → compare current version → update or 412.

Key Points

  • An ETag represents a version of a resource.
  • Keep dependencies and responsibilities explicit.
  • Cover error handling and edge cases in tests.
Q140Dependency Injection

What is a captive dependency?

A captive dependency occurs when a longer-lived service holds a shorter-lived service, such as a singleton capturing a scoped DbContext. This can

Answer

A captive dependency occurs when a longer-lived service holds a shorter-lived service, such as a singleton capturing a scoped DbContext. This can cause stale state, cross-request data leakage, or lifetime errors.

Apply the approach according to the application's constraints and verify important behavior with automated tests.

Syntax

Singleton → scoped dependency is usually invalid

Example

services.AddScoped<AppDbContext>(); services.AddSingleton<ReportCache>(); // do not constructor-inject AppDbContext here

Code example

services.AddScoped<AppDbContext>();\nservices.AddSingleton<ReportCache>(); // do not constructor-inject AppDbContext here

Diagram

Singleton lifetime ─X→ scoped DbContext; create a scope when scoped work is required.

Key Points

  • A captive dependency occurs when a longer-lived service holds a shorter-lived service, such as a singleton capturing a scoped DbContext.
  • Keep dependencies and responsibilities explicit.
  • Cover error handling and edge cases in tests.
Q143Asynchronous Programming

What does ConfigureAwait(false) do in library code?

ConfigureAwait(false) tells an await not to capture the current synchronization context for its continuation. It is commonly used in reusable lib

Answer

ConfigureAwait(false) tells an await not to capture the current synchronization context for its continuation. It is commonly used in reusable library code; ASP.NET Core normally has no classic request synchronization context.

Apply the approach according to the application's constraints and verify important behavior with automated tests.

Syntax

await operation.ConfigureAwait(false);

Example

public async Task<byte[]> DownloadAsync(Uri uri) { return await client.GetByteArrayAsync(uri).ConfigureAwait(false); }

Code example

public async Task<byte[]> DownloadAsync(Uri uri)\n{\n    return await client.GetByteArrayAsync(uri).ConfigureAwait(false);\n}

Diagram

Await operation → continuation may run without returning to captured context.

Key Points

  • ConfigureAwait(false) tells an await not to capture the current synchronization context for its continuation.
  • Keep dependencies and responsibilities explicit.
  • Cover error handling and edge cases in tests.
Q144Asynchronous Programming

When is System.Threading.Channels useful?

Channels provide asynchronous producer-consumer coordination with optional bounded capacity and backpressure. They are useful for background queu

Answer

Channels provide asynchronous producer-consumer coordination with optional bounded capacity and backpressure. They are useful for background queues inside a process, but are not a durable distributed message broker.

Apply the approach according to the application's constraints and verify important behavior with automated tests.

Syntax

Channel.CreateBounded<WorkItem>(capacity: 100)

Example

var channel = Channel.CreateBounded<WorkItem>(100); await channel.Writer.WriteAsync(item, ct); var next = await channel.Reader.ReadAsync(ct);

Code example

var channel = Channel.CreateBounded<WorkItem>(100);\nawait channel.Writer.WriteAsync(item, ct);\nvar next = await channel.Reader.ReadAsync(ct);

Diagram

Producer → bounded channel/backpressure → consumer.

Key Points

  • Channels provide asynchronous producer-consumer coordination with optional bounded capacity and backpressure.
  • Keep dependencies and responsibilities explicit.
  • Cover error handling and edge cases in tests.
Q148Design Patterns

How does the transactional outbox pattern prevent lost messages?

Write the business change and an outbox record in the same database transaction. A background publisher sends pending records and marks them proc

Answer

Write the business change and an outbox record in the same database transaction. A background publisher sends pending records and marks them processed; consumers should tolerate duplicates.

Apply the approach according to the application's constraints and verify important behavior with automated tests.

Syntax

BEGIN TRANSACTION; UPDATE Orders; INSERT OutboxMessages; COMMIT;

Example

await using var tx = await db.Database.BeginTransactionAsync(ct); db.Orders.Add(order); db.OutboxMessages.Add(OutboxMessage.ForOrderCreated(order)); await db.SaveChangesAsync(ct); await tx.CommitAsync(ct);

Code example

await using var tx = await db.Database.BeginTransactionAsync(ct);\ndb.Orders.Add(order);\ndb.OutboxMessages.Add(OutboxMessage.ForOrderCreated(order));\nawait db.SaveChangesAsync(ct);\nawait tx.CommitAsync(ct);

Diagram

Single DB transaction → business row + outbox row → publisher → broker → idempotent consumer.

Key Points

  • Write the business change and an outbox record in the same database transaction.
  • Keep dependencies and responsibilities explicit.
  • Cover error handling and edge cases in tests.
Q149Design Patterns

How does the Circuit Breaker pattern protect a dependent service?

A circuit breaker stops calls to a failing dependency after a threshold, waits for a recovery interval, then probes with limited calls. It comple

Answer

A circuit breaker stops calls to a failing dependency after a threshold, waits for a recovery interval, then probes with limited calls. It complements timeouts and retries rather than replacing them.

Apply the approach according to the application's constraints and verify important behavior with automated tests.

Syntax

Closed → Open → Half-open → Closed/Open

Example

var pipeline = new ResiliencePipelineBuilder() .AddCircuitBreaker(new CircuitBreakerStrategyOptions { FailureRatio = 0.5, MinimumThroughput = 8, SamplingDuration = TimeSpan.FromSeconds(10), BreakDuration = TimeSpan.FromSeconds(5) }) .Build();

Code example

var pipeline = new ResiliencePipelineBuilder()\n    .AddCircuitBreaker(new CircuitBreakerStrategyOptions\n    { FailureRatio = 0.5, MinimumThroughput = 8, SamplingDuration = TimeSpan.FromSeconds(10), BreakDuration = TimeSpan.FromSeconds(5) })\n    .Build();

Diagram

Repeated failures → open circuit rejects calls → half-open probe → close on recovery.

Key Points

  • A circuit breaker stops calls to a failing dependency after a threshold, waits for a recovery interval, then probes with limited calls.
  • Keep dependencies and responsibilities explicit.
  • Cover error handling and edge cases in tests.

Share this question bank

Send this page to someone preparing for an interview.