C# Language Interview Q&A

C# Language Interview Q&A

Explore c# language interview q&a code snippets and tutorials

C# Language Interview Q&A

ASP.NET Core request pipeline: Kestrel, middleware order, routing and endpoints

Middleware order matters.

csharp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
// ======================================================================
// Q: What happens to an HTTP request in ASP.NET Core?
//
// Middleware order matters. Common mistakes: UseAuthorization before
// UseAuthentication, or CORS after authentication.
// ======================================================================

Kestrel → middleware pipeline → routing → endpoint → response (back through the same middleware)

app.UseExceptionHandler();     // 1. first: catches the errors of everything after it
app.UseHsts();
app.UseHttpsRedirection();
app.UseStaticFiles();          // static files without auth and routing
app.UseRouting();
app.UseCors();
app.UseAuthentication();       // who you are (before authorization)
app.UseAuthorization();        // what is allowed
app.UseRateLimiter();
app.MapControllers();          // endpoint: model binding → filters → action
C# Language Interview Q&A

C# thread safety: lock, SemaphoreSlim, Interlocked and concurrent collections

Immutable data and no shared state: the best option.

csharp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
// ======================================================================
// Q: How do you make code thread-safe?
//
// - Immutable data and no shared state: the best option.
// - lock: for short critical sections. It does not allow await inside it (.NET
//   9+ has the System.Threading.Lock type).
// - SemaphoreSlim: for async critical sections or limiting concurrent
//   operations.
// - Interlocked: for atomic counters. ConcurrentDictionary, Channel<T> for
//   producer/consumer.
// - Watch out: a singleton service is shared across all requests, so it must be
//   thread-safe.
// ======================================================================

private readonly SemaphoreSlim _gate = new(1, 1);

public async Task RefreshTokenAsync(CancellationToken ct)
{
    await _gate.WaitAsync(ct);      // only one refresh at a time
    try { _token = await FetchTokenAsync(ct); }
    finally { _gate.Release(); }
}
C# Language Interview Q&A

C# parallelism: Task.WhenAll and Parallel.ForEachAsync with MaxDegreeOfParallelism

Parallel.For / PLINQ for CPU-bound work.

csharp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
// ======================================================================
// Q: How do you run work in parallel and limit concurrency?
//
// Parallel.For / PLINQ for CPU-bound work. Task.WhenAll with no limit over
// 10,000 items = 10,000 concurrent calls.
// ======================================================================

// Independent I/O calls: concurrently
var stockTask = erp.GetWarehouseStockAsync(sku, ct);
var daysTask  = erp.GetDeliveryDaysAsync(sku, ct);
await Task.WhenAll(stockTask, daysTask);          // time = the slowest one, not the sum

// Many items with a limit on concurrent calls (so you don't take down the ERP)
await Parallel.ForEachAsync(skus,
    new ParallelOptions { MaxDegreeOfParallelism = 4, CancellationToken = ct },
    async (sku, token) => await SyncPriceAsync(sku, token));
C# Language Interview Q&A

Modern C# features: primary constructors, collection expressions, pattern matching

Features used day to day: primary constructors and collection expressions (C# 12), required + init properties, switch expressions with patterns, property patterns, plus records, file-scoped namespaces, global usings and raw …

csharp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// ======================================================================
// Q: Which modern C# features do you use?
//
// Features used day to day: primary constructors and collection expressions (C#
// 12), required + init properties, switch expressions with patterns, property
// patterns, plus records, file-scoped namespaces, global usings and raw string
// literals.
// ======================================================================

public class OrderService(IOrderRepository repo, ILogger<OrderService> log) { }  // primary ctor (C# 12)
int[] ids = [1, 2, 3];                                       // collection expressions (C# 12)
public required string Sku { get; init; }                    // required + init
var label = status switch                                    // switch expression + patterns
{
    OrderStatus.Draft or OrderStatus.Placed => "Open",
    OrderStatus.Shipped                     => "Done",
    _                                       => "Other"
};
if (order is { Status: OrderStatus.Placed, TotalNet: > 1000 }) { /* property pattern */ }
// + records, file-scoped namespaces, global usings, raw string literals ("""...""")
C# Language Interview Q&A

C# IDisposable, IAsyncDisposable and using statements: why and when

For unmanaged or expensive resources (connections, file handles, streams) that must be released immediately, not whenever the GC runs.

csharp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// ======================================================================
// Q: IDisposable and using: why and when?
//
// For unmanaged or expensive resources (connections, file handles, streams) that
// must be released immediately, not whenever the GC runs. using calls Dispose
// even on an exception. IAsyncDisposable / await using for async cleanup.
// Whatever the DI container creates, the container disposes at the end of the
// scope. Do not Dispose injected services. Finalizers only if you directly hold
// an unmanaged handle (rare; usually SafeHandle).
// ======================================================================

await using var stream = File.OpenRead(path);   // Dispose at the end of the scope
using var activity = ActivitySource.StartActivity("ImportPrices");