A class uses reference equality by default: two objects with identical property values are normally unequal unless Equals is overridden. A record supplies value-based equality across its equality components. Whenever Equals says two values are equal, GetHashCode must return the same hash code. The reverse is not required because collisions are possible. Keys must also remain logically immutable while stored in a Dictionary or HashSet; changing a field used by equality can make an entry impossible to find.
For a class, implement IEquatable<T>, override object.Equals, and combine the same fields in GetHashCode:
```csharp
public sealed class ProductKey : IEquatable<ProductKey>
{
public required string Sku { get; init; }
public required int OutletId { get; init; }
public bool Equals(ProductKey? other) =>
other is not null && OutletId == other.OutletId &&
StringComparer.OrdinalIgnoreCase.Equals(Sku, other.Sku);
public override bool Equals(object? obj) => Equals(obj as ProductKey);
public override int GetHashCode() =>
HashCode.Combine(StringComparer.OrdinalIgnoreCase.GetHashCode(Sku), OutletId);
}
```
A concise alternative is `public sealed record ProductKey(string Sku, int OutletId);`. Use an explicit comparer when equality rules, such as case-insensitive text, differ from the type's defaults.
Records are data-focused types with generated value equality, readable `ToString`, and nondestructive mutation through `with`. An `init` accessor permits assignment during construction or object initialization but prevents normal reassignment afterward. These features reduce accidental mutation in DTOs, commands, configuration, and domain value objects.
```csharp
public sealed record CreateOrder(
Guid CustomerId,
IReadOnlyList<OrderLine> Lines);
public sealed record OrderLine
{
public required string Sku { get; init; }
public required int Quantity { get; init; }
public decimal UnitPrice { get; init; }
}
var original = new OrderLine
{
Sku = "COFFEE", Quantity = 1, UnitPrice = 120m
};
var corrected = original with { Quantity = 2 };
```
Immutability is not automatic all the way down: a record containing a mutable `List<T>` can still be changed, and record equality compares that list reference rather than each element. Prefer immutable collections or expose read-only abstractions, validate at the boundary, and use classes when identity and a controlled mutable lifecycle matter more than value equality.
`IEnumerable<T>` represents objects enumerated in .NET. LINQ-to-Objects delegates run in the process. `IQueryable<T>` carries an expression tree that a provider, such as EF Core, can translate into another query language. Execution is usually deferred until enumeration or a terminal operation.
```csharp
public async Task<IReadOnlyList<OrderSummary>> SearchAsync(
decimal minimum, CancellationToken ct)
{
return await db.Orders
.AsNoTracking() // IQueryable<Order>
.Where(order => order.Total >= minimum) // translated to SQL
.OrderByDescending(order => order.CreatedAt)
.Select(order => new OrderSummary(order.Id, order.Total))
.Take(50)
.ToListAsync(ct); // executes here
}
```
Calling `AsEnumerable` or `ToList` too early moves later filtering into memory and may fetch far more rows. Conversely, exposing `IQueryable` from an API or across layers leaks provider behavior and lets callers construct unbounded queries. Compose the database query inside the persistence boundary, project only required columns, execute asynchronously, and return a materialized read model.
A default interface method lets an interface add behavior without immediately breaking every implementation. An abstract class can hold instance state, define constructors, expose protected members, and combine abstract and implemented members. A class can implement multiple interfaces but inherit from only one base class.
```csharp
public interface IPriceRule
{
decimal Apply(decimal subtotal);
string Describe() => GetType().Name;
}
public abstract class AuditedRule
{
protected AuditedRule(ILogger logger) => Logger = logger;
protected ILogger Logger { get; }
public abstract decimal Apply(decimal subtotal);
}
```
Use an interface to describe a capability across unrelated types and keep consumers decoupled. Use an abstract base when implementations genuinely share state, invariants, construction logic, or protected behavior. Default interface implementations should be small and contract-oriented; they are not a substitute for a stateful base class. Also remember that a default method is normally called through the interface reference unless the class provides its own public member.
Reflection inspects metadata and interacts with types at runtime. It can discover assemblies, types, attributes, constructors, properties, and methods, and can create or invoke members dynamically. Frameworks use it for dependency registration, serialization, mapping, testing, and plugin discovery.
```csharp
[AttributeUsage(AttributeTargets.Class)]
public sealed class HandlerAttribute : Attribute { }
[Handler]
public sealed class PaymentHandler
{
public Task HandleAsync() => Task.CompletedTask;
}
var handlers = typeof(PaymentHandler).Assembly.GetTypes()
.Where(type => type.GetCustomAttribute<HandlerAttribute>() is not null)
.ToArray();
```
Reflection trades compile-time guarantees and speed for flexibility. Repeated `GetProperty` or `MethodInfo.Invoke` calls in a hot path can allocate and be slower than direct calls; cache metadata or compile delegates when measurement justifies it. Handle `ReflectionTypeLoadException` during broad assembly scanning, avoid invoking untrusted types, and consider trimming or Native AOT: members reachable only through reflection may require annotations or source-generated alternatives.
C# commonly demonstrates compile-time polymorphism through overload resolution and run-time polymorphism through virtual dispatch or interface dispatch. Parametric polymorphism through generics is also important because one algorithm works safely with many types.
```csharp
public sealed class PriceFormatter
{
public string Format(decimal value) => value.ToString("0.00");
public string Format(decimal value, string currency) =>
$"{currency} {value:0.00}"; // compile-time overload selection
}
public interface IDiscount
{
decimal Apply(decimal subtotal);
}
public sealed class PercentageDiscount(decimal rate) : IDiscount
{
public decimal Apply(decimal subtotal) => subtotal * (1 - rate);
}
static T Last<T>(IReadOnlyList<T> values) => values[^1]; // generic
```
When `IDiscount.Apply` is called, the runtime selects the concrete implementation. Overloading selects the best compatible signature at compile time. Method hiding with `new` is not overriding: selection depends on the reference's compile-time type, so it is usually less suitable for substitutable behavior.
`yield return` defines an iterator. The compiler generates a state machine that produces one value each time the consumer advances the enumerator. This enables lazy streaming without building the entire result collection. `yield break` ends iteration.
```csharp
public static IEnumerable<int> Fibonacci(int count)
{
if (count < 0) throw new ArgumentOutOfRangeException(nameof(count));
int current = 0;
int next = 1;
for (int index = 0; index < count; index++)
{
yield return current;
(current, next) = (next, checked(current + next));
}
}
foreach (int value in Fibonacci(7))
Console.WriteLine(value); // 0, 1, 1, 2, 3, 5, 8
```
The method body starts when enumeration begins, not when `Fibonacci` is called. Each enumeration runs it again. Resource cleanup in a `using` or `finally` still occurs when the enumerator is disposed, so consumers should dispose enumerators—`foreach` does this automatically. For asynchronous streams, use `async IAsyncEnumerable<T>` with `yield return` and consume using `await foreach`.
Start by defining the violated invariant, such as “payment is captured once” or “an order can transition from Pending to Confirmed only once.” Add correlation IDs and structured logs around reads, writes, versions, retries, and external calls. Reproduce with concurrent requests in a test that uses the real persistence boundary; a single-threaded unit test rarely exposes the race.
The durable fix normally belongs in the database, not only in an in-process lock. Use an atomic conditional update, unique constraint, transaction, or optimistic concurrency token:
```csharp
public async Task<bool> ConfirmAsync(Order order, CancellationToken ct)
{
order.Status = OrderStatus.Confirmed;
try
{
await db.SaveChangesAsync(ct); // RowVersion is checked by EF Core
return true;
}
catch (DbUpdateConcurrencyException)
{
return false; // Reload and decide whether the operation is already complete
}
}
```
Also make external operations idempotent by sending a stable operation key. Trace thread-pool metrics, but do not assume every async defect is a threading defect. Finally, verify the fix under repeated parallel load and confirm the stored state, not merely HTTP success responses.
Measure first. Observe allocation rate, heap size, Gen 0/1/2 collections, large-object-heap size, pause time, and request latency with `dotnet-counters`; capture a trace or dump to identify allocating call stacks and retained objects. A high allocation rate and a memory leak are different: a leak shows objects remaining reachable after collections.
Common reductions include avoiding repeated materialization, streaming large results, reusing buffers through `ArrayPool<T>`, removing unnecessary string conversions, and selecting collections with sensible capacity.
```csharp
public static async Task CopyAsync(Stream input, Stream output, CancellationToken ct)
{
byte[] buffer = ArrayPool<byte>.Shared.Rent(64 * 1024);
try
{
int read;
while ((read = await input.ReadAsync(buffer.AsMemory(0, buffer.Length), ct)) > 0)
await output.WriteAsync(buffer.AsMemory(0, read), ct);
}
finally
{
ArrayPool<byte>.Shared.Return(buffer, clearArray: true);
}
}
```
Do not pool small objects blindly; pooling adds lifetime and thread-safety complexity. Benchmark the changed hot path and confirm that allocation savings improve real latency or throughput rather than shifting cost elsewhere.
ASP.NET Core routing chooses endpoints from route templates, HTTP methods, and constraints—not from C# overload resolution alone. Constraints narrow candidates and should disambiguate shapes, not perform business validation.
```csharp
[ApiController]
[Route("api/orders")]
public sealed class OrdersController : ControllerBase
{
[HttpGet("{id:guid}")]
public IActionResult GetById(Guid id) => Ok(id);
[HttpGet("number/{number:int:min(1)}")]
public IActionResult GetByNumber(int number) => Ok(number);
}
```
Routes such as two `[HttpGet("{value}")]` actions—one taking `int`, another `string`—are ambiguous unless templates include constraints or distinct static segments. C# method signatures do not make the URLs unique. Use clear resource-oriented paths, apply `[FromRoute]`, `[FromQuery]`, or `[FromBody]` when binding could be unclear, and return normal validation errors after routing for domain rules. Integration-test representative and boundary URLs because link generation and endpoint selection are runtime behavior.
In a backend API, the main benefit is scalability during I/O waits. While the database, another service, or storage is working, an incomplete await allows the request thread to return to the pool instead of blocking. That thread can serve other requests. Async does not make the remote dependency faster; it uses server threads more efficiently.
```csharp
[HttpGet("{id:guid}")]
public async Task<ActionResult<OrderDto>> Get(
Guid id, CancellationToken ct)
{
var order = await db.Orders
.AsNoTracking()
.Where(item => item.Id == id)
.Select(item => new OrderDto(item.Id, item.Total))
.SingleOrDefaultAsync(ct);
return order is null ? NotFound() : Ok(order);
}
```
The benefit appears only when the whole path uses genuine asynchronous APIs. Calling `.Result`, `.Wait()`, or wrapping synchronous database I/O in `Task.Run` still consumes threads and can cause starvation under load. Pass request cancellation, apply timeouts, and measure throughput and latency.
`var` is compile-time type inference. The variable still has one specific static type, and invalid member access is a compile error. `dynamic` postpones member binding until runtime; the compiler permits the call, but it can fail with `RuntimeBinderException`. Neither keyword means “no type.”
```csharp
var customer = new Customer("Asha"); // statically Customer
Console.WriteLine(customer.Name); // checked at compile time
dynamic payload = GetLegacyComObject();
try
{
Console.WriteLine(payload.CustomerName); // resolved at runtime
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
logger.LogWarning(ex, "Unexpected legacy payload shape");
}
```
Prefer `var` when the assigned type is obvious and it improves readability, especially for anonymous types and LINQ projections. Use `dynamic` only at genuinely dynamic boundaries such as COM, some scripting systems, or legacy libraries. At JSON boundaries, typed DTOs or explicit `JsonElement` access are usually safer. `var value = GetDynamic()` still becomes dynamic if the expression's compile-time type is dynamic.
The .NET GC groups managed objects by age. New objects start in generation 0. Objects that survive a collection can be promoted to generation 1 and then generation 2. This generational design is efficient because most allocations die young, so Gen 0 can be collected frequently and cheaply while long-lived objects are scanned less often. Large objects normally go to the large object heap and are collected with Gen 2.
```csharp
long before = GC.GetAllocatedBytesForCurrentThread();
var values = Enumerable.Range(0, 10_000).ToArray();
long allocated = GC.GetAllocatedBytesForCurrentThread() - before;
Console.WriteLine($"Allocated: {allocated:N0} bytes");
```
Generation is not an ownership mechanism, and calling `GC.Collect()` in normal application code is usually harmful because it disrupts the GC's adaptive decisions. Dispose unmanaged-resource wrappers promptly with `using`; disposal and garbage collection solve different problems. Diagnose with counters, traces, or dumps, then reduce proven high-volume allocations or unintended retention.
ASP.NET Core exposes `HttpContext.RequestAborted`. Accept it as a `CancellationToken` action parameter and pass the same token through every cancellable layer. Cancellation is cooperative: each operation must observe the token. Do not replace it with `CancellationToken.None`, and do not convert a client disconnect into a generic server error.
```csharp
[HttpGet("{id:guid}")]
public async Task<ActionResult<OrderDto>> Get(
Guid id, CancellationToken cancellationToken)
{
var order = await repository.FindAsync(id, cancellationToken);
if (order is null) return NotFound();
using var request = new HttpRequestMessage(
HttpMethod.Get, $"risk/{order.CustomerId}");
using var response = await httpClient.SendAsync(request, cancellationToken);
response.EnsureSuccessStatusCode();
return Ok(Map(order));
}
```
For an application timeout, link it with the request token using `CancellationTokenSource.CreateLinkedTokenSource`, then call `CancelAfter`. Catch `OperationCanceledException` only when you can add meaning or distinguish timeout from caller cancellation; otherwise let the framework complete cancellation handling. Never reuse a disposed token source.
An async method runs synchronously until it reaches an incomplete await. It then returns a Task and registers the remainder as a continuation. `await` does not itself create a thread. For true asynchronous I/O, no application thread needs to remain blocked while the operation is pending.
```csharp
public async Task<Customer?> LoadAsync(int id, CancellationToken ct)
{
using var response = await http.GetAsync($"customers/{id}", ct);
if (response.StatusCode == HttpStatusCode.NotFound) return null;
response.EnsureSuccessStatusCode();
return await response.Content.ReadFromJsonAsync<Customer>(cancellationToken: ct);
}
```
Thread-pool starvation occurs when work is queued but available worker threads are blocked, often by `.Result`, `.Wait()`, synchronous I/O, or long locks. Prefer async all the way and pass cancellation tokens. Classic UI or legacy ASP.NET deadlocks can occur when synchronous code blocks a context thread while the awaited continuation needs that same context. ASP.NET Core does not install that synchronization context, but blocking still harms scalability. Use `async void` only for event handlers; otherwise return `Task` so callers can await completion and observe exceptions.
A lambda is an anonymous function. LINQ operators accept lambdas to filter, transform, order, and aggregate sequences. To return numbers divisible by `n`, validate that `n` is nonzero and use the remainder operator.
```csharp
public static IEnumerable<int> DivisibleBy(
IEnumerable<int> values, int divisor)
{
if (divisor == 0)
throw new ArgumentOutOfRangeException(nameof(divisor));
return values.Where(value => value % divisor == 0);
}
var result = DivisibleBy(Enumerable.Range(1, 20), 3).ToArray();
// 3, 6, 9, 12, 15, 18
```
`Where` is deferred: it stores the predicate and evaluates items when the result is enumerated. If the source can change and you need a snapshot, materialize with `ToArray` or `ToList`. For `IQueryable<T>`, the lambda becomes an expression tree and may be translated by the provider, so use expressions that provider supports. A simple loop may be clearer on a performance-critical hot path; measure rather than assuming LINQ is always too slow.
Multithreading is about execution on multiple threads. It can improve responsiveness or run CPU work in parallel on multiple cores, but shared state introduces races and synchronization costs. Async/await is about composing operations that may complete later without blocking the caller. It does not automatically create a thread.
```csharp
// I/O concurrency: operations overlap while waiting.
Task<string> a = http.GetStringAsync("catalog/a", ct);
Task<string> b = http.GetStringAsync("catalog/b", ct);
string[] pages = await Task.WhenAll(a, b);
// CPU parallelism: computation can use multiple worker threads.
Parallel.ForEach(files, file => ComputeHash(file));
```
Use asynchronous APIs for database, HTTP, file, and queue waits. Consider controlled parallelism for independent CPU-heavy work after measuring. The models can coexist: several asynchronous operations may resume on different thread-pool threads, and `Parallel.ForEachAsync` can coordinate asynchronous delegates. The key interview distinction is that async avoids blocked waiting, while parallel multithreading performs work simultaneously.
First clarify whether “second highest” means the second distinct salary or simply the second row after sorting. Interviewers usually mean the second distinct salary, so duplicate top salaries should count once.
```csharp
decimal? secondHighest = employees
.Select(employee => employee.Salary)
.Distinct()
.OrderByDescending(salary => salary)
.Skip(1)
.Cast<decimal?>()
.FirstOrDefault();
```
For EF Core, keep the query as `IQueryable` so filtering, distinct, ordering, and limiting are translated to SQL:
```csharp
decimal? secondHighest = await db.Employees
.Select(employee => employee.Salary)
.Distinct()
.OrderByDescending(salary => salary)
.Skip(1)
.Select(salary => (decimal?)salary)
.FirstOrDefaultAsync(ct);
```
The nullable result represents fewer than two distinct salaries. To return every employee earning that amount, compute the value first and then issue a second filtered query, or use an appropriate window-function query where supported.
Create a test project, reference the production project, arrange inputs and dependencies, execute one behavior, and assert the observable result. Keep unit tests deterministic and fast; use integration tests when the behavior depends on a real database, filesystem, queue, or HTTP boundary.
```bash
dotnet new xunit -n Shop.UnitTests
dotnet add Shop.UnitTests reference Shop.Application
dotnet test
```
```csharp
public sealed class PriceCalculatorTests
{
[Theory]
[InlineData(100, 0.10, 90)]
[InlineData(50, 0, 50)]
public void ApplyDiscount_ReturnsExpectedTotal(
decimal subtotal, decimal rate, decimal expected)
{
var sut = new PriceCalculator();
decimal actual = sut.ApplyDiscount(subtotal, rate);
Assert.Equal(expected, actual);
}
[Fact]
public void ApplyDiscount_RejectsNegativeSubtotal()
{
var sut = new PriceCalculator();
Assert.Throws<ArgumentOutOfRangeException>(
() => sut.ApplyDiscount(-1, 0.1m));
}
}
```
Name tests around behavior, cover boundaries and failure paths, and avoid asserting private implementation details. CI should run `dotnet test` from a clean checkout.
A delegate is a type-safe reference to a method. `Func<...>` represents a method that returns a value; `Action<...>` represents one that returns void. An event wraps a delegate with publisher/subscriber rules: outside code can subscribe or unsubscribe but cannot raise the event directly.
```csharp
public sealed record OrderPaid(Guid OrderId, decimal Amount);
public sealed class PaymentService
{
public event EventHandler<OrderPaid>? Paid;
public decimal CalculateTotal(
IEnumerable<decimal> lines, Func<decimal, decimal> discount)
{
var subtotal = lines.Sum();
return discount(subtotal);
}
public void MarkPaid(Guid id, decimal amount)
{
// Persist the payment first.
Paid?.Invoke(this, new OrderPaid(id, amount));
}
}
var service = new PaymentService();
service.Paid += (_, payment) =>
Console.WriteLine($"Receipt for {payment.OrderId}: {payment.Amount:C}");
```
Delegates are useful for strategies, callbacks, and composition. Events work for in-process notification, but they are not a durable message bus: subscribers can fail, disappear on restart, and retain objects if not unsubscribed. Use durable messaging for cross-service business events.