Top 15 Advance SQL Interview Questions for Senior .NET Professionals (2026 Edition)

As we navigate through 2026, the role of a .NET professional has transcended beyond simple CRUD operations. With the advent of AI-integrated databases, distributed microservices, and massive scale-out architectures, a senior developer's mastery of SQL must be sophisticated. Today’s interviews focus not just on syntax, but on performance tuning, architectural trade-offs, and the seamless integration between EF Core 10/11 and modern relational engines.

1. How do Common Table Expressions (CTEs) differ from Temporary Tables in terms of execution and scope?

CTEs are non-persistent result sets that exist only during the execution of a single query. They improve readability but are generally re-evaluated each time they are referenced in the main query unless the optimizer materializes them. Temporary Tables (#Temp), however, are stored in TempDB and persist for the duration of a session, allowing for indexing which makes them superior for large datasets requiring multiple passes.

In a .NET 2026 context, using LINQ with EF Core often translates queries into CTEs. Here is how we might handle a recursive organizational structure using a CTE translated from a C# service layer:


// Using EF Core 10+ to execute a raw SQL recursive CTE for hierarchy
public async Task<List<EmployeeNode>> GetEmployeeHierarchyAsync(int rootId)
{
    var query = @"
        WITH EmpCTE AS (
            SELECT Id, Name, ManagerId, 0 AS Level
            FROM Employees WHERE Id = {0}
            UNION ALL
            SELECT e.Id, e.Name, e.ManagerId, Level + 1
            FROM Employees e
            INNER JOIN EmpCTE pct ON e.ManagerId = pct.Id
        )
        SELECT * FROM EmpCTE";

    return await _context.Database.SqlQueryRaw<EmployeeNode>(query, rootId).ToListAsync();
}
  

2. Explain the impact of SARGability on Query Performance.

SARGable (Search ARGumentable) queries allow the SQL engine to effectively use indexes. Using functions on indexed columns in a WHERE clause (e.g., WHERE YEAR(OrderDate) = 2026) makes the query non-SARGable, forcing an index scan instead of a seek. Senior developers must ensure that their LINQ expressions do not generate non-SARGable SQL.

3. How do Window Functions like ROW_NUMBER(), RANK(), and DENSE_RANK() differ?

These functions are vital for analytical reporting without using heavy GROUP BY clauses. ROW_NUMBER() assigns a unique sequential integer. RANK() provides the same rank for ties but leaves gaps in the sequence. DENSE_RANK() provides the same rank for ties without leaving gaps. In 2026, these are frequently used in .NET for implementing complex pagination and "Top N per Category" logic.

4. Discuss Indexing Strategies: Clustered vs. Non-Clustered vs. Columnstore.

A Clustered index defines the physical order of data. Non-Clustered indexes are separate structures pointing to the data. However, for 2026's Big Data requirements, Columnstore Indexes are the standard for analytical workloads (OLAP) as they compress data by columns rather than rows, significantly reducing I/O for aggregate queries.

5. How do you handle Distributed Transactions in a Microservices architecture using the Saga Pattern?

With the decline of MSDTC (Microsoft Distributed Transaction Coordinator) in cloud-native environments, SQL-based consistency is handled via the Saga Pattern. Instead of a single ACID transaction, we use a series of local transactions with compensating logic. In .NET, libraries like MassTransit or NServiceBus are used to manage these state machines.


// Example of a local transaction within a Saga step using EF Core
public async Task ProcessOrderStep(OrderContext context)
{
    using var transaction = await _dbContext.Database.BeginTransactionAsync();
    try 
    {
        _dbContext.Orders.Update(context.Order);
        await _dbContext.SaveChangesAsync();
        
        // Publish event to the next microservice
        await _bus.Publish(new OrderProcessedEvent(context.OrderId));
        
        await transaction.CommitAsync();
    }
    catch (Exception) 
    {
        await transaction.RollbackAsync();
        // Trigger Compensating Transaction logic
    }
}
  

6. Explain SQL Server Temporal Tables and their use cases in .NET auditing.

Temporal Tables (System-Versioned tables) automatically track every change made to data, storing history in a parallel table. This is the modern replacement for manual audit triggers. In EF Core, you can configure these fluently to ensure your .NET entities support point-in-time recovery and auditing natively.

7. What are the differences between Optimistic and Pessimistic Concurrency?

Pessimistic concurrency locks data at the database level, preventing others from accessing it (high contention). Optimistic concurrency, the preferred approach in modern web apps, uses a RowVersion or Timestamp column. The update fails if the version has changed since the data was read.


// EF Core Optimistic Concurrency handling
try 
{
    await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException ex) 
{
    foreach (var entry in ex.Entries) 
    {
        var databaseValues = await entry.GetDatabaseValuesAsync();
        // Logic to resolve conflict: Client Wins or Database Wins
        entry.OriginalValues.SetValues(databaseValues);
    }
}
  

8. Describe the use of JSON functions in SQL (JSON_VALUE, OPENJSON) vs. NoSQL.

Modern relational databases are now "multi-model." We store semi-structured data in JSONB (Postgres) or NVARCHAR(MAX) with JSON constraints (SQL Server). This allows for schema flexibility within a structured environment. EF Core 9+ provides deep support for mapping owned types to JSON columns.

9. What is the "N+1 Query Problem" and how do you profile it in a .NET application?

The N+1 problem occurs when an application executes one query to fetch parent records and then N additional queries to fetch children for each parent. This is mitigated by using .Include() (Eager Loading) or .Select() projections. Profiling is done via OpenTelemetry, SQL Server Profiler, or EF Core's built-in logging.

10. How do Vector Indexes work in SQL for AI-driven applications?

By 2026, many SQL engines (like Azure SQL or pgvector) support vector data types. This allows developers to store "embeddings" (mathematical representations of text/images) and perform similarity searches using cosine distance directly in SQL, enabling RAG (Retrieval-Augmented Generation) workflows.

11. Explain Transaction Isolation Levels and their side effects.

Interviewers look for an understanding of:

  • Read Uncommitted: Dirty reads.
  • Read Committed: Default; prevents dirty reads.
  • Repeatable Read: Prevents non-repeatable reads but allows phantoms.
  • Serializable: Full isolation, highest overhead.
  • Snapshot: Uses row versioning to provide consistency without locking.

12. How do you optimize a query that is performing a "Scan" instead of a "Seek"?

An Index Scan reads the entire index, while a Seek jumps directly to the rows. Scans are caused by non-SARGable queries, missing indexes, or low selectivity. Solutions include adding "Covering Indexes" (using INCLUDE columns) and updating statistics to help the Query Optimizer.

13. Discuss the difference between CROSS APPLY and INNER JOIN.

CROSS APPLY is conceptually similar to a correlated subquery but more efficient. It allows you to join a table to a Table-Valued Function (TVF) or a subquery that references columns from the outer table, which is impossible with a standard INNER JOIN.

14. What are Deadlocks and how can you minimize them in high-concurrency .NET apps?

A deadlock occurs when two sessions hold locks that the other needs. To minimize them: access objects in a consistent order, keep transactions short, use READ COMMITTED SNAPSHOT isolation, and ensure proper indexing to reduce the number of locks held.

15. How do Materialized Views differ from standard Views?

A standard view is a virtual query. A Materialized View (or Indexed View) physically stores the result set on disk. This dramatically speeds up heavy aggregation queries but adds overhead during Insert/Update/Delete operations on the base tables because the view must be updated synchronously or asynchronously.

Conclusion

Mastering SQL in 2026 requires a deep understanding of how the database engine interacts with modern C# frameworks and cloud infrastructure. By focusing on performance, concurrency, and modern data types like JSON and Vectors, senior developers can build resilient and scalable backend systems. The key is not just knowing how to write a query, but understanding how that query behaves under load in a distributed ecosystem.


About the Author: Mohd Nasir Siddqui is a .NET software professional with 10 years of experience specializing in scalable backend architectures and modern web applications.

Top 20 .NET Core Interview Questions 2026

The .NET ecosystem has undergone a massive transformation as we head into 2026. With the maturity of .NET 10 and the stabilization of cloud-native orchestration through .NET Aspire, the expectations for senior developers have shifted. It is no longer just about knowing C# syntax; it is about mastering distributed systems, AI integration, Native AOT, and extreme performance optimization. This guide covers the top 20 interview questions designed for senior-level positions in the current landscape.

1. How does Native AOT in .NET 10 impact cloud-native deployment compared to JIT?

Native Ahead-of-Time (AOT) compilation has become a standard for high-scale microservices. Unlike the Just-In-Time (JIT) compiler, Native AOT compiles C# directly into machine code at build time. This results in faster startup times, reduced memory footprint (no JIT infrastructure in memory), and smaller self-contained executables. In 2026, developers must be aware of the "trimming" limitations—reflection and dynamic assembly loading are restricted in AOT environments.


// Example of a minimal API optimized for Native AOT
var builder = WebApplication.CreateSlimBuilder(args);

// SlimBuilder excludes features not compatible with AOT by default
builder.Services.ConfigureHttpJsonOptions(options =>
{
    options.SerializerOptions.TypeInfoResolver = MyContext.Default;
});

var app = builder.Build();
app.MapGet("/", () => "Optimized for AOT");
app.Run();

[JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(string))]
internal partial class MyContext : JsonSerializerContext { }
  

2. What is .NET Aspire, and how does it simplify distributed application development?

.NET Aspire is an opinionated, cloud-ready stack for building observable, production-ready distributed applications. It provides a way to orchestrate resources (databases, caches, messaging) and automatically configures service discovery, telemetry, and health checks. By 2026, senior developers are expected to use Aspire to manage the complexity of multi-container local development and cloud deployments.

3. Explain the role of Semantic Kernel in modern .NET AI applications.

With AI-driven features becoming ubiquitous, Semantic Kernel (SK) acts as the orchestration layer between .NET applications and Large Language Models (LLMs). It allows developers to define "Plugins" and "Kernels" that wrap AI prompts as standard C# methods, enabling seamless integration of GenAI into traditional business logic.


// Simple Semantic Kernel setup in 2026
var kernel = Kernel.CreateBuilder()
    .AddOpenAIChatCompletion("gpt-5", apiKey)
    .Build();

// Defining a function that the AI can invoke
kernel.ImportPluginFromFunctions("HelperPlugin", new[]
{
    kernel.CreateFunctionFromMethod(() => DateTime.Now.ToString(), "GetCurrentTime")
});

var result = await kernel.InvokePromptAsync("What time is it and why is .NET 10 great?");
Console.WriteLine(result);
  

4. How do Keyed Services in Dependency Injection solve the "Multiple Implementation" problem?

Introduced in recent versions, Keyed Services allow developers to register multiple implementations of the same interface and retrieve them using a unique key. This eliminates the need for complex factory patterns when dealing with different service providers (e.g., having different storage implementations for Azure vs. AWS in the same app).


// Registration
builder.Services.AddKeyedScoped<IMessageService, SmsService>("sms");
builder.Services.AddKeyedScoped<IMessageService, EmailService>("email");

// Usage in a Controller or Service
public class NotificationController([FromKeyedServices("sms")] IMessageService smsService)
{
    public IActionResult Send() 
    {
        smsService.SendMessage("Hello via Keyed DI");
        return Ok();
    }
}
  

5. Describe the performance benefits of FrozenCollections in .NET.

Frozen collections (FrozenDictionary and FrozenSet) are optimized for read-heavy scenarios where the collection is created once and never modified. They perform significantly faster lookup operations than standard concurrent or immutable collections because the internal data structure is specialized for fixed keys.

6. What are Primary Constructors in C# 12/13/14, and how do they impact boilerplate?

Primary constructors allow you to define constructor parameters directly in the class or struct declaration. This drastically reduces the boilerplate code required to assign private readonly fields, making the code cleaner and more readable for dependency injection.


// Modern approach with Primary Constructors
public class ProductService(IDbContext dbContext, ILogger<ProductService> logger)
{
    public async Task GetProducts()
    {
        logger.LogInformation("Fetching products...");
        return await dbContext.Products.ToListAsync();
    }
}
  

7. How does the 'TimeProvider' abstraction improve unit testing?

The TimeProvider class provides a mockable way to handle time-dependent logic (DateTime.Now, Task.Delay, etc.). Instead of relying on the system clock, which makes tests flaky, developers can inject a TimeProvider and manually advance time in their unit tests.

8. Explain the "HybridCache" library introduced to the .NET ecosystem.

HybridCache bridges the gap between IMemoryCache (L1) and IDistributedCache (L2, like Redis). It handles complex scenarios like "stampede protection" (ensuring only one request fetches data if the cache is empty) and provides a unified API for multi-level caching strategies.

9. What are C# Interceptors, and how are they used in source generators?

Interceptors are a compiler feature that allows a source generator to redirect a specific method call to a different piece of code. This is heavily used by frameworks like ASP.NET Core to optimize Minimal APIs, replacing runtime reflection with static code redirection at build time.

10. How does 'SearchValues' optimize string and span searching?

SearchValues<T> is a high-performance type designed for searching sets of values within a Span. It uses SIMD (Single Instruction, Multiple Data) instructions under the hood to perform searches much faster than traditional methods like string.IndexOfAny.


// Pre-computing search values for performance
private static readonly SearchValues<char> DisallowedChars = SearchValues.Create("!@#$%^&*");

public bool IsValid(ReadOnlySpan<char> input)
{
    // High-performance check using SIMD instructions
    return input.IndexOfAny(DisallowedChars) == -1;
}
  

11. Discuss the evolution of Minimal APIs vs. Controllers in 2026.

In 2026, Minimal APIs are the default choice for high-performance microservices and Native AOT applications. Controllers are still used in legacy monoliths or complex UI-heavy applications. Minimal APIs now support almost all controller features (filters, binding, versioning) while offering better performance and less overhead.

12. What is the significance of "Chiseled" Ubuntu images for .NET containers?

Chiseled images are ultra-small, hardened container images that contain only the necessary runtime components—no shell, no package manager, and no unnecessary binaries. This significantly reduces the attack surface and image size, making them the gold standard for secure .NET deployments in Kubernetes.

13. How do you implement Resilience Pipelines using Microsoft.Extensions.Resilience?

Moving away from the older Polly syntax, .NET now provides a built-in resilience library. It allows developers to define strategies like retries, circuit breakers, and timeouts using a centralized builder pattern that integrates with the DI container.


// Defining a resilience pipeline
var pipeline = new ResiliencePipelineBuilder()
    .AddRetry(new RetryStrategyOptions
    {
        MaxRetryAttempts = 3,
        BackoffType = DelayBackoffType.Exponential
    })
    .AddTimeout(TimeSpan.FromSeconds(5))
    .Build();

await pipeline.ExecuteAsync(async token => await CallExternalService(token));
  

14. Explain 'ValueTask' vs 'Task' and when to use which in 2026.

Task is a class and results in a heap allocation. ValueTask is a struct and can avoid allocation if the operation completes synchronously. For high-throughput services, ValueTask is preferred for methods that frequently return cached results or complete immediately.

15. How does EF Core 10 handle "Compiled Queries" automatically?

EF Core 10 has improved its query compilation engine to automatically cache and reuse the generated SQL for most LINQ queries without requiring manual EF.CompileQuery calls. This reduces the overhead of the LINQ-to-SQL translation process significantly.

16. What is the 'System.Diagnostics.Metrics' API and how does it relate to OpenTelemetry?

The Metrics API is a built-in way to record numerical measurements (e.g., request count, memory usage). It is designed to be highly efficient and is the standard source for OpenTelemetry exporters to scrape data for tools like Prometheus and Grafana.

17. Describe the "Discriminated Unions" proposal and its state in C#.

While still a hot topic in 2026, Discriminated Unions (DUs) allow for a type to be one of several different types (e.g., Result = Success(data) | Error(message)). Developers use records and switch expressions to simulate DUs, providing a more functional approach to error handling and state management.

18. How does .NET 10 improve Garbage Collection for high-memory machines?

Recent updates to the GC include "Regional GC" and "Dynamic Adaptation to Application Sizes" (DATAS). These allow the GC to manage memory more granularly in environments with hundreds of gigabytes of RAM, reducing pause times and improving throughput for massive data-processing nodes.

19. What is "Middleware Filtering" in Minimal APIs?

Endpoint filters allow developers to run code before or after a Minimal API handler executes. This is the modern equivalent of "Action Filters" in MVC and is used for validation, logging, and security checks.


app.MapGet("/secure-data", () => "Sensitive Info")
   .AddEndpointFilter(async (context, next) =>
   {
       if (context.HttpContext.Request.Headers["X-Auth"] != "Valid")
       {
           return Results.Unauthorized();
       }
       return await next(context);
   });
  

20. How do you secure .NET 10 APIs using OAuth 2.1 best practices?

In 2026, OAuth 2.1 is the standard. This involves deprecating the "Implicit Grant" flow in favor of "Authorization Code Flow with PKCE" (Proof Key for Code Exchange). Developers must ensure that all tokens are validated using strongly typed configuration and that sensitive data is protected via "JWE" (JSON Web Encryption) where necessary.

Conclusion

The .NET landscape of 2026 demands a deep understanding of cloud-native primitives and high-performance coding patterns. By mastering these 20 concepts, you demonstrate not only technical proficiency but also an ability to build scalable, secure, and modern applications that leverage the full power of the .NET 10+ ecosystem. Success in a senior interview today relies on proving you can balance cutting-edge features like AI and AOT with the foundational principles of clean architecture and system reliability.


About the Author: Mohd Nasir Siddqui is a .NET software professional with 10 years of experience specializing in scalable backend architectures and modern web applications.

Top 15 Advanced SQL Interview Questions for Senior .NET Professionals in 2026

As we navigate the architectural landscapes of 2026, the role of a senior .NET developer has transcended simple CRUD operations. Modern distributed systems, AI-integrated databases, and high-scale cloud-native applications demand a profound understanding of SQL. It is no longer just about writing queries; it is about performance engineering, data integrity in microservices, and mastering the bridge between Entity Framework (EF) Core and the underlying relational engine.

This guide compiles the top 15 advanced SQL interview questions, focusing on deep technical concepts and their practical application within the .NET ecosystem.

1. How do Window Functions differ from Aggregate Functions, and how do you implement them in EF Core?

Aggregate functions (like SUM or AVG) collapse rows into a single result based on a group. Window functions, however, perform calculations across a set of table rows that are somehow related to the current row, without collapsing them. In 2026, EF Core has matured significantly in its translation of window functions.

// Example of using EF Core to perform a Window Function calculation
var orders = await context.Orders
    .Select(o => new 
    {
        o.OrderId,
        o.OrderDate,
        o.Amount,
        RunningTotal = EF.Functions.Sum(o.Amount, EF.Functions.Over().PartitionBy(o.CustomerId).OrderBy(o.OrderDate))
    })
    .ToListAsync();

2. Explain the concept of SARGability and why it is critical for performance tuning.

SARGable (Search ARGumentable) queries are those where the SQL engine can effectively use indexes. A common mistake is wrapping a column in a function, which prevents index seeks. For example, WHERE YEAR(OrderDate) = 2026 is not SARGable, whereas WHERE OrderDate >= '2026-01-01' AND OrderDate < '2027-01-01' is.

3. How do you handle Hierarchical Data in SQL, and when would you use Recursive CTEs?

Recursive Common Table Expressions (CTEs) are essential for querying tree structures, such as organizational charts or category taxonomies. In a .NET environment, you might fetch this data to build a navigation tree.


// C# method to execute a recursive CTE via Raw SQL for efficiency
public async Task<List<CategoryHierarchy>> GetCategoryTreeAsync()
{
    var sql = @"
        WITH CategoryTree AS (
            SELECT Id, Name, ParentId, 0 AS Level
            FROM Categories WHERE ParentId IS NULL
            UNION ALL
            SELECT c.Id, c.Name, c.ParentId, ct.Level + 1
            FROM Categories c
            INNER JOIN CategoryTree ct ON c.ParentId = ct.Id
        )
        SELECT * FROM CategoryTree";

    return await _context.CategoryHierarchies.FromSqlRaw(sql).ToListAsync();
}
  

4. Discuss the difference between Clustered and Non-Clustered Indexes in the context of Columnstore Indexes.

While traditional B-tree indexes are row-store, Columnstore indexes (introduced for OLAP) store data column-wise. In 2026, many high-performance .NET applications use "Clustered Columnstore" indexes for large-scale telemetry or historical data to achieve massive compression and query speedups for aggregation-heavy workloads.

5. What are Temporal Tables, and how does EF Core facilitate "Point-in-Time" analysis?

Temporal tables (System-Versioned tables) allow SQL Server to automatically track the history of data changes. This is vital for auditing and "undo" features in modern SaaS platforms.


// Querying a temporal table in EF Core to find the state of an entity at a specific time
var historicalProduct = await context.Products
    .TemporalAsOf(DateTime.Parse("2025-01-01"))
    .Where(p => p.Id == productId)
    .FirstOrDefaultAsync();
  

6. Explain Transaction Isolation Levels and how to mitigate "Snapshot Isolation" overhead.

Isolation levels (Read Uncommitted, Read Committed, Repeatable Read, Serializable, and Snapshot) define how transactions are isolated from one another. Snapshot isolation uses row versioning in tempdb to prevent blocking, which is preferred for high-concurrency .NET applications but requires monitoring tempdb growth.

7. How do you implement Row-Level Security (RLS) for Multi-tenant Applications?

RLS shifts the responsibility of data isolation from the application code to the database. By creating a security policy and a predicate function, you ensure that a .NET database context only sees data belonging to the current tenant, typically identified by a SESSION_CONTEXT value.

8. What is the impact of N+1 Query problems, and how do you detect them using modern tools?

The N+1 problem occurs when an application makes N additional database calls to fetch related data for each primary record. Beyond .Include(), senior developers use QuerySplittingBehavior.SplitQuery in EF Core to prevent Cartesian explosions when joining multiple collections.

9. Compare `MERGE` vs. `UPSERT` logic using EF Core’s `ExecuteUpdate` and `ExecuteDelete`.

The MERGE statement can be prone to concurrency issues. Modern EF Core (v7+) provides ExecuteUpdate and ExecuteDelete, which perform bulk operations directly on the database without loading entities into memory, effectively acting as high-performance "upsert" components.


// Efficiently updating multiple records without loading them into the Change Tracker
await context.Products
    .Where(p => p.Discontinued)
    .ExecuteUpdateAsync(s => s.SetProperty(p => p.Price, p => p.Price * 0.9m));
  

10. How does Vector Search in SQL Server (or Azure SQL) support modern AI/LLM integration?

By 2026, SQL Server has robust support for vector data types. This allows developers to store embeddings generated by AI models and perform "cosine similarity" searches directly within SQL, rather than relying on external vector databases.

11. Describe the "Deadlock" scenario and how you would analyze a Deadlock Graph.

A deadlock occurs when two transactions hold locks that the other needs. Analyzing the XML Deadlock Graph helps identify the "victim." In .NET, implementing a RetryingExecutionStrategy is the standard approach to handle transient deadlock failures gracefully.

12. What are the trade-offs of using `sp_getapplock` for distributed locking?

When you need to synchronize tasks across multiple instances of a microservice, sp_getapplock allows you to use the SQL Server engine as a distributed lock manager. It is lighter than Redis for small-scale applications but can increase database contention.

13. How do you handle JSON data within a Relational Schema?

Modern SQL supports JSON_VALUE, JSON_QUERY, and OPENJSON. This hybrid approach allows for schema flexibility (storing dynamic metadata) while maintaining relational integrity for core entities.


// Querying a JSON column in SQL Server via EF Core
var users = await context.Users
    .Where(u => EF.Functions.JsonValue(u.ExtendedProperties, "$.Theme") == "Dark")
    .ToListAsync();
  

14. Explain Database Sharding vs. Horizontal Partitioning.

Horizontal partitioning (Table Partitioning) splits a table within a single database instance (e.g., by date), whereas Sharding distributes data across multiple physical database instances. Senior architects must decide based on the scale—partitioning for manageability, sharding for extreme throughput.

15. How do Execution Plans help in identifying "Implicit Conversion" issues?

Implicit conversion happens when the data types of a predicate do not match the column type (e.g., comparing a VARCHAR parameter to a NVARCHAR column). This triggers a conversion of every row in the column, destroying index performance. The execution plan will show a warning icon on the Select or Compute Scalar operator.

Conclusion

Mastering SQL at a senior level requires more than just knowing syntax; it requires an understanding of how the database engine interacts with your .NET application code. By focusing on execution plans, concurrency models, and modern features like temporal tables and vector search, you position yourself as a vital asset for any high-performance engineering team in 2026. Stay curious, profile your queries, and always remember that the most efficient code is the code that minimizes unnecessary data movement between the database and the application. This comprehensive understanding will ensure you excel in your next senior technical interview.


About the Author: Mohd Nasir Siddqui is a .NET software professional with 10 years of experience specializing in scalable backend architectures and modern web applications.

Top 20 .NET Core Interview Questions 2026

As we navigate through 2026, the .NET ecosystem has evolved into a high-performance, cloud-native powerhouse. With .NET 10 and 11 setting new benchmarks for productivity and efficiency, senior developers are expected to understand more than just syntax. This guide covers the most critical interview questions designed for senior roles, focusing on Native AOT, cloud-native orchestration with .NET Aspire, advanced performance tuning, and architectural patterns.

1. How has Native AOT (Ahead-of-Time) compilation changed the deployment strategy for .NET microservices in 2026?

Native AOT has become a standard for serverless and containerized workloads. Unlike JIT (Just-In-Time) compilation, Native AOT compiles C# directly into machine code at publish time. This results in significantly faster startup times and lower memory footprints because the JIT compiler and its overhead are removed from the runtime.


// Example: Enabling Native AOT in a .csproj file
// <PropertyGroup>
//   <PublishAot>true</PublishAot>
//   <OptimizationPreference>Speed</OptimizationPreference>
// </PropertyGroup>

// Using AOT-compatible JSON serialization
[JsonSerializable(typeof(Todo[]))]
internal partial class AppJsonSerializerContext : JsonSerializerContext { }
  

2. What is .NET Aspire, and how does it simplify modern distributed application development?

.NET Aspire is an opinionated, cloud-ready stack for building observable, production-ready, distributed applications. In 2026, it is the primary way to manage service discovery, telemetry, and resilience in a microservices ecosystem without manual configuration overhead.


// In the AppHost Program.cs
var builder = DistributedApplication.CreateBuilder(args);

var redis = builder.AddRedis("cache");
var apiService = builder.AddProject<Projects.ApiService>("apiservice");

builder.AddProject<Projects.WebFrontend>("webfrontend")
    .WithReference(redis)
    .WithReference(apiService);

builder.Build().Run();
  

3. Explain the "HybridCache" library introduced in recent .NET versions.

HybridCache bridges the gap between in-memory (IMemoryCache) and distributed caching (IDistributedCache). It provides a unified API that handles L1 (local) and L2 (remote) caching layers automatically, preventing "cache stampedes" through built-in locking mechanisms.


// Using HybridCache to fetch data with a fallback
public async Task<Product> GetProductAsync(int id, CancellationToken token)
{
    return await _hybridCache.GetOrCreateAsync(
        $"product_{id}",
        async cancel => await _db.Products.FindAsync(id, cancel),
        cancellationToken: token
    );
}
  

4. How do Interceptors in C# 14/15 impact performance and library design?

Interceptors allow source generators to "reroute" specific method calls at compile time to optimized versions. This is widely used in Minimal APIs and DTO mapping to eliminate reflection entirely, leading to near-instantaneous execution of framework code.


// Conceptual Interceptor usage (handled by Source Generators)
[InterceptsLocation("Program.cs", line: 42, column: 15)]
public static void MyInterceptorMethod(this IEndpointRouteBuilder builder)
{
    // Optimized logic that replaces the original MapGet call
}
  

5. Discuss the Dynamic Adaptation to Application Sizes (DATAS) in the .NET 10+ Garbage Collector.

DATAS is a major evolution in the GC. Previously, developers had to choose between Workstation and Server GC. DATAS allows the GC to dynamically adjust its memory footprint based on the application's actual throughput and resource constraints, making it ideal for environments where container memory limits vary.

6. What are "Frozen Collections" and when should you use them?

FrozenDictionary and FrozenSet are specialized collections introduced for read-heavy scenarios. Once created, they are immutable and optimized for extremely fast lookups. They are ideal for configuration data or look-up tables that are initialized at startup.


// Creating a FrozenDictionary for fast lookup
private static readonly FrozenDictionary<string, string> ConfigMap = 
    new Dictionary<string, string> { { "Key1", "Value1" } }.ToFrozenDictionary();

public string GetValue(string key) => ConfigMap.GetValueOrDefault(key);
  

7. How does Keyed Service support in Dependency Injection improve software architecture?

Keyed services allow developers to register multiple implementations of the same interface and resolve them using a unique key. This eliminates the need for complex factory patterns or manual resolution logic.


// Registration
builder.Services.AddKeyedSingleton<IMessageService, SmsService>("sms");
builder.Services.AddKeyedSingleton<IMessageService, EmailService>("email");

// Injection
public class NotificationHandler([FromKeyedServices("sms")] IMessageService smsService)
{
    // Uses SmsService implementation
}
  

8. Explain the concept of "Vertical Slice Architecture" over Traditional N-Tier Architecture.

In 2026, many senior developers prefer Vertical Slices. Instead of grouping by technical concerns (Controllers, Services, Repositories), code is grouped by business features. This reduces coupling and makes it easier to modify or scale specific features without affecting the whole system.

9. What is the role of SearchValues<T> in high-performance string processing?

SearchValues<T> provides a highly optimized way to search for specific sets of characters or bytes within a span. It uses SIMD (Single Instruction, Multiple Data) under the hood to perform searches much faster than traditional IndexOfAny calls.


// Pre-calculating search values for valid tokens
private static readonly SearchValues<char> ValidTokens = SearchValues.Create("ABC123");

public bool ContainsInvalid(ReadOnlySpan<char> input)
{
    // Returns true if input contains anything NOT in ValidTokens
    return input.IndexOfAnyExcept(ValidTokens) != -1;
}
  

10. Describe the latest security best practices for protecting .NET APIs in 2026.

Modern security focuses on "Zero Trust." This includes using Managed Identities to eliminate connection strings, implementing OAuth 2.1, and using "Strict-Transport-Security" headers. Additionally, the use of `DataProtection` for sensitive payloads in distributed environments is mandatory.

11. How do you handle distributed transactions in a .NET microservices environment?

The industry has shifted away from two-phase commits toward the **Saga Pattern**. Using tools like MassTransit or NServiceBus, we implement sequences of local transactions where each step triggers the next via events. If a step fails, "compensating transactions" are triggered to undo previous work.

12. What is the difference between `IEnumerable`, `IQueryable`, and `IAsyncEnumerable` in 2026?

`IEnumerable` is for in-memory collections; `IQueryable` is for database-level filtering (LINQ-to-SQL); `IAsyncEnumerable` is used for streaming data from a source asynchronously, which is vital for high-concurrency web applications to prevent thread starvation.


// Streaming records from a database
public async IAsyncEnumerable<UserDto> StreamUsersAsync([EnumeratorCancellation] CancellationToken ct)
{
    await foreach (var user in _context.Users.AsAsyncEnumerable().WithCancellation(ct))
    {
        yield return new UserDto(user.Name);
    }
}
  

13. Explain "TimeProvider" and why it is essential for unit testing.

The `TimeProvider` abstraction (introduced in .NET 8) allows developers to mock time. This makes testing logic dependent on time (like delays, timeouts, or timestamps) predictable and fast, without using `Thread.Sleep`.


// Injecting TimeProvider for testability
public class GracePeriodService(TimeProvider timeProvider)
{
    public bool IsExpired(DateTimeOffset createdAt) =>
        timeProvider.GetUtcNow() - createdAt > TimeSpan.FromDays(7);
}
  

14. How does EF Core 10 handle "Compiled Models" for startup optimization?

Compiled Models allow EF Core to pre-generate the metadata required to map entities to the database at build time. This dramatically reduces the "First Query" latency, which is often a bottleneck in cold-start scenarios like Azure Functions or AWS Lambda.

15. Describe the "Circuit Breaker" pattern and how to implement it using Polly.

The Circuit Breaker prevents a system from repeatedly trying to execute an operation that is likely to fail. In 2026, this is usually integrated via the `Microsoft.Extensions.Http.Resilience` library, which wraps Polly.


// Adding resilience in Program.cs
builder.Services.AddHttpClient("ExternalApi")
    .AddStandardResilienceHandler(options => {
        options.CircuitBreaker.MinimumThroughput = 10;
        options.CircuitBreaker.FailureRatio = 0.5;
    });
  

16. What is the "Options Pattern" and why is it preferred over raw configuration access?

The Options Pattern provides strongly-typed access to configuration groups. It supports validation (via DataAnnotations) and hot-reloading (via IOptionsSnapshot), ensuring that the application doesn't start with invalid settings.

17. How do you implement Rate Limiting in .NET Core 10/11?

.NET provides built-in rate-limiting middleware. You can choose from Fixed Window, Sliding Window, Token Bucket, or Concurrency algorithms to protect your API from abuse.


// Middleware configuration
app.UseRateLimiter(new RateLimiterOptions()
    .AddFixedWindowLimiter("policyName", opt => {
        opt.PermitLimit = 100;
        opt.Window = TimeSpan.FromMinutes(1);
    }));
  

18. What are "Required Members" and "Init-only Properties" in C#?

Required members ensure that a property must be set during object initialization, while `init` ensures it cannot be changed after creation. This facilitates safer, immutable data structures in DDD (Domain Driven Design).


public class User
{
    public required string Username { get; init; }
    public required string Email { get; init; }
}
  

19. How does .NET 11 optimize memory using "Params Collections"?

Newer versions of C# allow the `params` keyword to work with `ReadOnlySpan` and other collection types, reducing heap allocations when passing variable arguments to methods.


// Zero-allocation params usage
public void ProcessData(params ReadOnlySpan<int> numbers)
{
    foreach (var num in numbers) { /* ... */ }
}
  

20. What is the significance of OpenTelemetry in modern .NET applications?

OpenTelemetry is the industry standard for observability. .NET has deep integration with it, allowing developers to emit traces, metrics, and logs in a vendor-neutral format. This is crucial for debugging complex issues in distributed systems in 2026.

Conclusion

Mastering these topics demonstrates that you are not just a developer, but a technical leader capable of building scalable, efficient, and maintainable systems in the 2026 .NET landscape. Focus on understanding the "why" behind these features, as senior roles prioritize architectural decision-making and performance optimization over simple implementation tasks. Staying updated with Native AOT, Aspire, and modern C# enhancements is your key to excelling in your next technical interview.


About the Author: Mohd Nasir Siddqui is a .NET software professional with 10 years of experience specializing in scalable backend architectures and modern web applications.

Top 15 Advanced SQL Interview Questions for .NET Professionals (2026 Edition)

As we move into 2026, the role of a senior .NET developer has transcended beyond simple CRUD operations. With the proliferation of distributed systems, AI-integrated databases, and cloud-native architectures, senior technical interviews now focus on high-scale data integrity, performance tuning, and modern SQL features. This guide covers the top 15 advanced SQL interview questions designed to test your architectural depth and implementation skills within the .NET ecosystem.

1. How do Window Functions differ from GROUP BY clauses in high-performance reporting?

Window functions allow you to perform calculations across a set of table rows that are somehow related to the current row, without collapsing the result set into a single row. This is vital for 2026 data analytics where real-time streaming data needs context (like moving averages or running totals) without losing the individual transaction details.


// Using EF Core to execute a Window Function via Raw SQL
var report = await _context.Orders
    .FromSqlRaw(@"SELECT OrderId, Amount, 
                  SUM(Amount) OVER (PARTITION BY CustomerId ORDER BY OrderDate) as RunningTotal
                  FROM Orders")
    .ToListAsync();

2. Explain the use cases and performance implications of Recursive Common Table Expressions (CTEs).

Recursive CTEs are essential for querying hierarchical data structures, such as organizational charts or multi-level category trees in e-commerce platforms. In 2026, they are often used to traverse graph-like structures within relational databases before handing data off to AI models.


// C# example: Calling a stored procedure that uses a recursive CTE
// for an organizational hierarchy
public async Task<List<EmployeeNode>> GetOrgStructureAsync(int managerId)
{
    return await _context.Employees
        .FromSqlInterpolated($"EXEC GetEmployeeHierarchy {managerId}")
        .ToListAsync();
}

3. Describe the "N+1 Query Problem" and how to identify it using modern .NET profiling tools.

The N+1 problem occurs when an application makes N additional database calls to fetch related data for every primary record retrieved. In modern .NET (EF Core 10+), we mitigate this using Eager Loading (Include), Explicit Loading, or Query Splitting for large datasets to avoid Cartesian product explosions.


// Optimization: Using AsSplitQuery() to avoid Cartesian explosion in EF Core
var blogs = await _context.Blogs
    .Include(b => b.Posts)
    .Include(b => b.Contributors)
    .AsSplitQuery() // 2026 Best Practice for complex relationships
    .ToListAsync();

4. How do Vector Indexes work in SQL Server (2025+ versions) and how do they integrate with Semantic Kernel?

In 2026, SQL Server has robust support for Vector types to support RAG (Retrieval-Augmented Generation). Vector indexes allow for "Nearest Neighbor" searches on embeddings generated by LLMs. Senior developers must know how to store these embeddings as `VECTOR` data types and query them using cosine similarity.


// Storing and querying vector embeddings in .NET
public async Task<List<Product>> FindSimilarProducts(float[] embedding)
{
    string vectorJson = JsonSerializer.Serialize(embedding);
    return await _context.Products
        .FromSqlInterpolated($"SELECT TOP 5 * FROM Products ORDER BY VECTOR_DISTANCE(Embedding, {vectorJson}, 'cosine')")
        .ToListAsync();
}

5. What is the difference between Snapshot Isolation and Read Committed Snapshot Isolation (RCSI)?

RCSI provides statement-level consistency, while Snapshot Isolation provides transaction-level consistency. In high-concurrency .NET applications, RCSI is often enabled at the database level to prevent readers from blocking writers without the overhead of full serializability.

6. Explain the concept of "Columnstore Indexes" and when to use them over B-Tree indexes.

Columnstore indexes store data by column rather than by row. This is the gold standard for OLAP (Analytical) workloads in 2026. While B-Tree (Clustered) indexes are best for finding specific records, Columnstore indexes are optimized for scanning large datasets and performing aggregations.

7. How do you implement Optimistic Concurrency in EF Core using RowVersion/Timestamp?

To prevent the "last-in-wins" scenario in distributed systems, we use a `rowversion` column. EF Core automatically checks this version during `SaveChangesAsync()`, throwing a `DbUpdateConcurrencyException` if the record has been modified by another process.


// Entity Configuration
public class Product {
    public int Id { get; set; }
    [Timestamp]
    public byte[] Version { get; set; } // Database-managed rowversion
}

// Handling the exception in C#
try {
    await _context.SaveChangesAsync();
} catch (DbUpdateConcurrencyException ex) {
    // Logic to resolve conflict (merge or reload)
}

8. Discuss the use of Temporal Tables for auditing and point-in-time recovery.

Temporal tables (System-Versioned tables) allow SQL Server to automatically track the history of data changes. This is highly relevant for 2026 compliance standards (GDPR, SOC2), allowing developers to query what data looked like at any specific timestamp directly through EF Core.


// Querying a Temporal Table in EF Core
var historicalProduct = await _context.Products
    .TemporalAsOf(DateTime.UtcNow.AddMonths(-1))
    .SingleAsync(p => p.Id == productId);

9. How do Query Interceptors in EF Core help in performance monitoring?

Interceptors allow you to inject custom logic into the execution of SQL commands. In 2026, they are commonly used for dynamic sharding, fine-grained logging, or automatically adding query hints for specific performance scenarios.


// A simple Command Interceptor for logging slow queries
public class SlowQueryInterceptor : DbCommandInterceptor {
    public override ValueTask<DbDataReader> ReaderExecutingAsync(
        DbCommand command, CommandEventData eventData, DbDataReader result) {
        if (eventData.Duration > TimeSpan.FromSeconds(2)) {
            // Log slow query details
        }
        return base.ReaderExecutingAsync(command, eventData, result);
    }
}

10. What are the advantages of JSON Path expressions in SQL for modern microservices?

With the shift toward Document-Relational hybrids, SQL Server's ability to query JSON stored in `NVARCHAR(MAX)` or the native `JSON` type (introduced in recent versions) allows microservices to store semi-structured data while maintaining the ACID guarantees of a relational database.

11. Explain "Deadlock Victim" selection and how to minimize deadlocks in high-traffic APIs.

SQL Server chooses a deadlock victim based on the "Deadlock Priority" or the cost of rolling back the transaction. To minimize this in .NET, ensure that all transactions access tables in the same order, keep transactions short, and use appropriate isolation levels.

12. How does Distributed SQL (like Azure SQL Managed Instance or Cosmos DB for PostgreSQL) affect query design?

In 2026, scaling horizontally is common. Developers must design queries with "Distribution Keys" (Sharding keys) in mind. A query that doesn't include the distribution key may result in a "cross-shard fan-out," significantly degrading performance in a distributed environment.

13. Describe the difference between Materialized Views and Standard Views.

Standard views are virtual and run the underlying query every time. Materialized views (Indexed Views) store the result set physically. In 2026, these are used for complex aggregations in dashboards where data is updated frequently but read-latency must be sub-millisecond.

14. How do you handle "Bulk Operations" in EF Core without performance degradation?

Native EF Core now supports `ExecuteUpdate` and `ExecuteDelete`, which perform set-based operations directly on the database without loading entities into memory. This is a critical performance optimization for senior developers.


// Bulk Update in EF Core (2026 approach)
await _context.Products
    .Where(p => p.Category == "Legacy")
    .ExecuteUpdateAsync(s => s.SetProperty(p => p.IsActive, false));

15. What is the "Parameter Sniffing" problem and how do you resolve it?

Parameter sniffing occurs when SQL Server creates an execution plan based on the first parameter value passed, which might not be optimal for subsequent values. This is resolved using query hints like `OPTIMIZE FOR UNKNOWN` or `RECOMPILE`, or by using local variables within stored procedures.

Mastering these advanced SQL concepts is essential for navigating the complex data landscape of 2026. By understanding the intersection of deep database internals and the .NET runtime, you can build systems that are not only functional but also exceptionally scalable and performant. Advanced technical proficiency in SQL remains the most significant differentiator for senior software professionals in the modern era.

Introduction

As we navigate the software landscape of 2026, .NET 10 has solidified its position as the premier framework for cross-platform, cloud-native development. For senior developers and architects, the interview process has shifted away from basic syntax toward deep architectural patterns, performance optimization, and the integration of AI-driven workflows. This guide covers the top 20 interview questions designed to challenge even the most seasoned .NET professionals.

1. Explain the evolution of Native AOT in .NET 10 and its impact on cold-start performance.

Native AOT (Ahead-of-Time) compilation has matured significantly by 2026. Unlike the JIT (Just-In-Time) compiler, Native AOT compiles your code directly into machine code at publish time. This eliminates the need for the JIT compiler at runtime, resulting in faster startup times and lower memory footprints, which is critical for serverless environments and containerized microservices.

// Example of a minimal API optimized for Native AOT
// In 2026, we ensure all libraries used are "trim-ready"
using System.Text.Json.Serialization;

var builder = WebApplication.CreateSlimBuilder(args);

// Source generators are mandatory for JSON serialization in AOT
builder.Services.ConfigureHttpJsonOptions(options =>
{
    options.SerializerOptions.TypeInfoResolver = AppJsonContext.Default;
});

var app = builder.Build();
app.MapGet("/", () => "AOT Optimized Response");
app.Run();

[JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(string))]
internal partial class AppJsonContext : JsonSerializerContext { }

2. How does the "Modular Monolith" architecture compare to Microservices in the 2026 .NET ecosystem?

In 2026, many organizations have pivoted back from microservices to Modular Monoliths to reduce operational complexity. In .NET, this is achieved through strictly decoupled projects or folders, using internal libraries and shared kernels, and communicating via in-memory event buses or MediatR, while retaining the ability to split into microservices if scaling requirements demand it.

3. Describe the role of Semantic Kernel in modern .NET AI integration.

Semantic Kernel is now the standard SDK for integrating Large Language Models (LLMs) into .NET applications. It allows developers to orchestrate AI "plugins," manage memory (vector databases), and create "planners" that can automatically execute sequences of C# functions based on natural language prompts.

// Integrating an AI plugin with Semantic Kernel
using Microsoft.SemanticKernel;

var kernel = Kernel.CreateBuilder()
    .AddAzureOpenAIChatCompletion("model-id", "endpoint", "key")
    .Build();

// Defining a native function for the AI to call
kernel.ImportPluginFromFunctions("HelperPlugin", new[]
{
    kernel.CreateFunctionFromMethod((string input) => 
        $"Processed: {input}", "ProcessData")
});

// The AI can now invoke 'ProcessData' based on intent

4. What are "Primary Constructors" in C# and how have they evolved for classes?

Introduced in earlier versions and refined by 2026, primary constructors allow you to define constructor parameters directly in the class header. This reduces boilerplate and simplifies dependency injection for services.

// Dependency Injection using Primary Constructors
public class OrderService(IOrderRepository repository, ILogger<OrderService> logger)
{
    public async Task ProcessOrder(Guid id)
    {
        logger.LogInformation("Processing order {Id}", id);
        var order = await repository.GetByIdAsync(id);
        // ... business logic
    }
}

5. Explain the concept of "Zero-Copy" parsing with Span<T> and Utf8JsonReader.

Performance-critical applications in 2026 avoid heap allocations by utilizing Span<T> and ReadOnlySpan<T>. When parsing JSON or large text streams, Utf8JsonReader works directly with memory buffers without creating intermediate string objects, drastically reducing GC pressure.

6. How does .NET 10 handle Distributed Tracing and OpenTelemetry by default?

Observability is baked into the framework. .NET 10 provides first-class support for OpenTelemetry via the System.Diagnostics.DiagnosticSource and Activity classes. Middleware automatically captures traces and exports them to collectors like Jaeger or Honeycomb without requiring extensive manual instrumentation.

7. What is the difference between "Required" members and "Init-only" properties?

The required keyword ensures that a property must be set during object initialization, providing a compile-time safety net. init properties allow setting a value only during initialization, making the object immutable thereafter. In 2026, these are used together to create robust Data Transfer Objects (DTOs).

public class UserDto
{
    public required Guid Id { get; init; }
    public required string Email { get; init; }
    public string? DisplayName { get; init; }
}

// This will throw a compile error if Email is missing
var user = new UserDto { Id = Guid.NewGuid(), Email = "dev@example.com" };

8. Discuss the impact of Green IT and Carbon-Aware SDKs in .NET.

Sustainability has become a key metric. Modern .NET libraries now offer carbon-aware scheduling, where non-critical background tasks (via IHostedService) are delayed until the local energy grid has a higher percentage of renewable energy, often integrated through specialized cloud-native APIs.

9. How do "Extension Types" (C# 14/15 feature) differ from Extension Methods?

Extension Types allow developers to add new members—including properties and static methods—to existing types without using the traditional static class syntax. This provides a cleaner, more object-oriented way to extend third-party libraries.

10. Describe the "Vertical Slice Architecture" and why it is replacing N-Tier.

Vertical Slice Architecture organizes code by features rather than technical concerns (UI, Business, Data). Each feature "slice" contains everything from the API endpoint to the database logic, reducing the need to jump across projects and minimizing the "Change Ripple" effect.

11. What is the purpose of the FrozenDictionary<TKey, TValue>?

Introduced for high-performance scenarios, FrozenDictionary is an immutable collection optimized for read-heavy workloads. It performs significantly faster than ReadOnlyDictionary because it builds a highly optimized lookup structure at creation time.

using System.Collections.Frozen;

var source = new Dictionary<string, int> { { "A", 1 }, { "B", 2 } };
// Created once, read many times with O(1) performance
var optimizedConfig = source.ToFrozenDictionary(); 

12. Explain "Interceptors" in C# and their use in source generation.

Interceptors allow source generators to "intercept" calls to specific methods and redirect them to optimized versions. This is used heavily in ASP.NET Core to replace runtime reflection with compile-time generated logic for things like routing and dependency injection.

13. How do you implement Resilience Patterns using the modern Polly v8+ SDK?

Polly has evolved to be more performance-oriented with a functional "Resilience Pipeline" approach. This allows for combining retries, circuit breakers, and rate limiters into a single, cohesive execution policy.

// Defining a resilience pipeline in .NET 10
var pipeline = new ResiliencePipelineBuilder()
    .AddRetry(new RetryStrategyOptions
    {
        MaxRetryAttempts = 3,
        BackoffType = DelayBackoffType.Exponential
    })
    .AddCircuitBreaker(new CircuitBreakerStrategyOptions { ... })
    .Build();

await pipeline.ExecuteAsync(async token => await CallRemoteService(token));

14. What are "Discriminated Unions" in C# and how do they benefit Error Handling?

Expected to be a major feature by 2026, Discriminated Unions allow a method to return one of several different types. This replaces the "Result" pattern or throwing exceptions for flow control, making domain logic more explicit.

// Speculative syntax for 2026
public union Result<T> { T Value; Error Failure; }

public Result<User> GetUser(int id)
{
    var user = _db.Find(id);
    return user != null ? user : new Error("Not Found");
}

// Usage with pattern matching
var result = GetUser(1);
var message = result switch {
    User u => $"Found {u.Name}",
    Error e => $"Error: {e.Message}"
};

15. Explain the shift from Newtonsoft.Json to System.Text.Json for legacy migration.

By 2026, System.Text.Json is the default and only recommendation due to its performance and AOT compatibility. Migration involves handling missing features like polymorphic serialization through JsonPolymorphic attributes and custom JsonConverter implementations.

16. How does the "BFF" (Backend for Frontend) pattern apply to Blazor WebAssembly in 2026?

Blazor applications now predominantly use the BFF pattern to handle authentication and API aggregation. The Blazor WASM client only communicates with its specific ASP.NET Core host, which manages Secure Cookies and OIDC flows, mitigating XSS and token theft risks.

17. What is "Rate Limiting" middleware in ASP.NET Core and how does it prevent DoS?

The built-in Rate Limiting middleware allows developers to define policies (Fixed Window, Sliding Window, Token Bucket) to restrict the number of requests a user or IP can make, ensuring system stability under heavy load.

18. Describe the use of IAsyncEnumerable<T> in Streaming APIs.

For large data sets, IAsyncEnumerable<T> allows the server to stream results to the client as they are read from the database, reducing memory spikes and improving perceived performance.

// Streaming data from a repository to the API response
[HttpGet("stream")]
public async IAsyncEnumerable<DataPoint> GetLargeData()
{
    using var reader = await _db.ExecuteReaderAsync("SELECT * FROM Logs");
    while (await reader.ReadAsync())
    {
        yield return new DataPoint(reader["Value"].ToString());
    }
}

19. What are "Collection Expressions" and how do they improve code readability?

Introduced in C# 12 and ubiquitous by 2026, collection expressions provide a unified syntax [] for creating arrays, lists, and spans, allowing the compiler to choose the most efficient implementation.

// Unified collection syntax
int[] array = [1, 2, 3];
List<string> list = ["A", "B", "C"];
ReadOnlySpan<char> span = ['h', 'e', 'l', 'l', 'o'];

// Spread operator in collections
int[] extra = [0, ..array, 4]; // [0, 1, 2, 3, 4]

20. How does .NET 10 approach "Shadow Database Mirroring" for Zero-Downtime Deployments?

In high-availability systems, .NET 10 integrates with EF Core to support shadow mirroring where migrations are applied to a secondary schema and verified before the production traffic is toggled, ensuring database schema changes never cause application downtime.

Conclusion

The .NET ecosystem in 2026 is defined by extreme performance, AI integration, and a focus on developer productivity through language simplification. Mastering these topics—from Native AOT and Semantic Kernel to advanced C# features—is essential for any senior professional aiming to lead technical teams in the current era. By focusing on architectural patterns and the underlying mechanics of the framework, you will be well-prepared to tackle any challenge presented in a high-level technical interview.