Dotnet Csharp Interview Questions Scenario Based 2025 Interview Questions & Answers

20 questions available

Q1:

What is the difference between Task, ValueTask, and IAsyncEnumerable?

Mid

Answer

Task: Always allocates; best for long-running async operations. ValueTask: Avoids allocation when result is synchronous; but dangerous if awaited twice. IAsyncEnumerable: Async streaming; uses await foreach and yields values over time.
Q2:

Explain how the .NET ThreadPool decides when to add or remove worker threads.

Mid

Answer

.NET uses the Hill Climbing Algorithm: Measures throughput Adjusts thread count dynamically Increases threads until throughput drops Then finds an optimal stable point ThreadPool adapts to CPU cores, blocking calls, and workload patterns.
Q3:

What problem does the new Memory<T> & Span<T> solve?

Mid

Answer

They eliminate unnecessary memory allocations: Work with stack/heap/native memory No copying of buffers High-performance parsing, serialization, pipelines Span cannot escape the stack ? improves safety & performance.
Q4:

Why does async void cause hidden exceptions and race conditions?

Mid

Answer

Because: Exceptions bypass the caller and crash the process Caller cannot await completion Execution becomes fire-and-forget Only valid for event handlers.
Q5:

What is the difference between struct, readonly struct, ref struct, and record struct?

Mid

Answer

struct ? value type readonly struct ? immutable + avoids defensive copies ref struct ? must remain on stack (e.g., Span) record struct ? value semantics + synthesized equality
Q6:

Explain how .NET GC uses generations and LOH (Large Object Heap).

Mid

Answer

Generations: Gen0 ? short-lived objects Gen1 ? mid-lived Gen2 ? long-lived (full GC expensive) LOH: Objects > 85 KB Not compacted by default ? fragmentation .NET 5+ adds optional LOH compaction.
Q7:

How does .NET handle async state machines internally?

Mid

Answer

When using async/await: Compiler generates a hidden state machine struct Stores: locals awaiters continuation context Executes via MoveNext() Optimized heavily in .NET 7/8.
Q8:

What scenarios cause deadlocks when using async/await?

Mid

Answer

Common deadlock scenario: var x = Task.Run(() => DoWorkAsync()).Result; Because: UI/ASP.NET sync context waits Async method attempts to resume on same context Results in deadlock Fix: Use ConfigureAwait(false) Avoid .Result or .Wait().
Q9:

Why is lock(this) and lock(typeof(Class)) dangerous?

Mid

Answer

Because: External callers may also lock the same reference Causes global deadlocks Exposes private synchronization Use: private readonly object _lock = new();
Q10:

How does IServiceProvider resolve scoped vs singleton vs transient in ASP.NET Core?

Mid

Answer

Singleton ? one instance for entire application Scoped ? one instance per web request Transient ? new instance every resolution DI container creates an object graph and disposes scoped services at request end.
Q11:

What is the difference between IAsyncDisposable and IDisposable?

Mid

Answer

DisposeAsync allows async cleanup (DB, IO, network). Works with: await using var x = new Resource(); Useful for pooled or high-latency resources.
Q12:

Why does string interpolation sometimes degrade performance?

Mid

Answer

Because: $"{a}{b}" creates: Hidden string builder Extra allocations For high-performance logging: logger.LogInformation("Value {a} {b}", a, b);
Q13:

What is the difference between yield return and IAsyncEnumerable?

Mid

Answer

yield return: Synchronous iterator Lazily returns data IAsyncEnumerable: Async streaming Requires await foreach Ideal for large data sets over network/DB.
Q14:

Why is reflection slow and how do Source Generators fix performance?

Mid

Answer

Reflection: Scans metadata Creates objects dynamically Costly per call Source Generators: Compile-time code generation Zero reflection Used in System.Text.Json, DI, gRPC.
Q15:

What situations break value-type equality in C#?

Mid

Answer

Custom struct overriding Equals() incorrectly: Ignoring fields Not overriding GetHashCode() Mutable fields changing after insert in dictionary.
Q16:

What is the “sync context” in ASP.NET Core and why does it not exist?

Mid

Answer

ASP.NET Core does NOT use SynchronizationContext. It uses TaskScheduler.Default ? no thread affinity. Prevents deadlocks typical in MVC/WebForms.
Q17:

How does Kestrel achieve high throughput?

Mid

Answer

Uses libuv (older) or managed sockets (newer) Zero-copy pipeline I/O polling Pooled buffers Single writer per connection Multiple event loops Designed for millions of requests.
Q18:

Why is System.Text.Json faster than Newtonsoft.Json?

Mid

Answer

Span-based parsing No boxing/unboxing Source-generated serializers Fewer virtual calls Less reflection Less memory churn.
Q19:

What is the difference between worker service and hosted service?

Mid

Answer

IHostedService: Background process inside ASP.NET Core host Worker Service: Template for standalone background apps Uses generic host Ideal for schedulers, queues, Kafka, RabbitMQ.
Q20:

What causes thread starvation in .NET and how do you diagnose it?

Mid

Answer

Causes: Too many blocking calls Long-running sync code on threadpool Misconfigured MinThreads Tasks queued faster than executed Diagnosis: dotnet-trace PerfView Visual Studio Concurrency.