Top Interview Questions
.NET is a free, open-source, and versatile developer platform created by Microsoft that allows developers to build a wide range of applications, from web and mobile applications to desktop and cloud-based solutions. Since its initial release in the early 2000s, .NET has evolved significantly, becoming a robust framework that supports multiple programming languages, libraries, and tools.
The primary goal of .NET is to simplify the development process by providing a consistent environment for building applications and managing system resources efficiently. It abstracts the complexities of operating system-level interactions, memory management, and cross-platform deployment, allowing developers to focus more on application logic rather than low-level programming tasks.
The .NET framework was introduced by Microsoft in 2002 to modernize Windows application development. Initially, it was designed as a proprietary framework for building Windows desktop and web applications. Over the years, it evolved significantly:
.NET Framework (2002): The original version, primarily for Windows desktop and server applications. It included languages like C#, VB.NET, and F#.
.NET Core (2016): Introduced as an open-source, cross-platform framework to run applications on Windows, macOS, and Linux. It emphasized performance, modularity, and cloud readiness.
.NET 5/6/7/8 (2020 onwards): Unified platform replacing .NET Framework and .NET Core, combining their features into a single cross-platform ecosystem called ".NET." The current version (.NET 8, 2025) emphasizes high performance, cloud-native development, and scalability.
.NET has several features that make it a preferred choice for enterprise and modern application development:
With .NET Core and later unified .NET versions, developers can write code once and run it on multiple platforms, including Windows, macOS, Linux, Android, and iOS. This reduces duplication of effort and accelerates deployment.
.NET supports several programming languages including:
C#: The most widely used language for .NET applications.
VB.NET: Primarily used in legacy Windows applications.
F#: Functional programming language for complex computations.
C++/CLI: For integration with native code.
.NET provides a consistent object-oriented programming model across all types of applications. Developers can use a common set of libraries (Base Class Library - BCL) to handle file operations, database access, XML processing, web services, and more.
With features like Just-In-Time (JIT) compilation, ahead-of-time compilation, garbage collection, and runtime optimizations, .NET ensures high-performance execution for both web and desktop applications.
.NET offers built-in security features such as code access security, role-based security, encryption, and authentication mechanisms to protect applications from unauthorized access.
The framework is designed to support applications ranging from small desktop apps to large-scale cloud solutions. It integrates easily with microservices, containers, and cloud platforms such as Microsoft Azure.
Visual Studio, Visual Studio Code, and JetBrains Rider provide excellent development environments with features like debugging, code completion, profiling, and integrated testing for .NET applications.
.NET is built on a layered architecture that simplifies application development and deployment:
The CLR is the heart of the .NET framework. It provides services such as:
Memory management: Automatic garbage collection.
Exception handling: Uniform error handling mechanism.
Security: Code verification and access control.
Interoperability: Interaction with unmanaged code (e.g., C/C++ libraries).
The BCL provides a rich set of reusable classes and APIs for common tasks such as:
File and network I/O.
Data access (ADO.NET).
Collections, strings, and data types.
XML and JSON processing.
Threading and asynchronous programming.
.NET supports multiple application types:
ASP.NET: For web applications and APIs.
Windows Forms (WinForms): For desktop GUI applications.
WPF (Windows Presentation Foundation): For rich client applications.
Xamarin / MAUI: For cross-platform mobile applications.
Blazor: For building interactive web UIs using C# instead of JavaScript.
.NET allows developers to create a variety of applications:
ASP.NET Core allows developers to build high-performance, cross-platform web apps and REST APIs. It supports MVC (Model-View-Controller) architecture, Razor Pages, and Web APIs.
WinForms and WPF enable developers to create rich desktop applications for Windows with interactive UIs, multimedia support, and robust event-driven programming.
.NET MAUI (Multi-platform App UI) and Xamarin allow building native mobile apps for iOS and Android using a single codebase.
.NET integrates seamlessly with Microsoft Azure and other cloud services for scalable, distributed applications. Features like microservices, serverless computing, and containerization are fully supported.
.NET supports game development with libraries like MonoGame and Unity (C# scripting), enabling cross-platform gaming experiences.
With .NET IoT libraries, developers can build applications for sensors, devices, and embedded systems.
.NET Core and later versions are ideal for building microservices due to modularity, lightweight containers, and cross-platform deployment.
.NET integrates with Azure DevOps, Kubernetes, Docker, and CI/CD pipelines for cloud-native solutions.
.NET provides ML.NET for machine learning, allowing developers to train, evaluate, and deploy models using C# and F#.
Blazor allows building full-stack web apps with C# instead of JavaScript, making it easier for .NET developers to create interactive front-end applications.
Consistency: Same development experience across different application types.
Performance: Optimized runtime for high throughput and low latency.
Productivity: Powerful IDEs, extensive libraries, and NuGet package manager.
Security: Strong authentication, encryption, and code verification.
Community Support: Large developer community, extensive documentation, and open-source contributions.
Interoperability: Can integrate with native code and third-party libraries.
Answer:
.NET is a software framework developed by Microsoft that provides a controlled programming environment where software can be developed, installed, and executed on Windows-based operating systems. It provides a large set of libraries, tools, and runtime environments for building various applications like desktop, web, mobile, and cloud applications.
Key points:
Supports multiple languages like C#, VB.NET, and F#.
Provides a Common Language Runtime (CLR) for executing applications.
Offers Base Class Library (BCL) for common functionalities.
| Feature | .NET Framework | .NET Core |
|---|---|---|
| Platform | Windows only | Cross-platform (Windows, Linux, macOS) |
| Open Source | No (mostly) | Yes |
| Performance | Good | High performance & lightweight |
| Deployment | Installed on OS | Can be deployed with app (self-contained) |
| Application Type | Web forms, WPF, Windows services | Web APIs, Console apps, Microservices |
Note: .NET 5/6/7 is the unified platform combining .NET Core and .NET Framework features.
Answer:
CLR is the execution engine for .NET applications. It provides services like:
Memory management (Garbage Collection)
Security (Code Access Security)
Exception handling
Type safety
Just-In-Time (JIT) compilation
Think of CLR as the virtual machine that runs your .NET application.
Managed Code: Runs under the control of CLR. Benefits include garbage collection, type safety, and security. Example: C#, VB.NET.
Unmanaged Code: Runs directly on Windows OS, not under CLR. Example: C++, Windows API calls.
Answer:
CTS defines all the data types and rules for declaring, using, and managing types in .NET. It ensures language interoperability, meaning different .NET languages can understand and use each other's types.
Example:
int in C# is compatible with Integer in VB.NET because CTS defines them as the same type.
| Feature | Stack | Heap |
|---|---|---|
| Storage | Value types | Reference types |
| Allocation | Static | Dynamic |
| Lifetime | Till method execution | Till Garbage Collection |
| Access Speed | Fast | Slower |
Value types (int, float, bool) are stored in stack, whereas reference types (objects, arrays) are stored in heap.
Value types: Store actual data, stored in stack. Examples: int, char, struct, enum.
Reference types: Store reference (address) to data, stored in heap. Examples: class, interface, string, array.
== and .Equals() in C#?== compares values for value types and references for reference types (unless overloaded).
.Equals() method compares content or value, can be overridden in classes.
Example:
string a = "hello";
string b = "hello";
Console.WriteLine(a == b); // True
Console.WriteLine(a.Equals(b)); // True
Answer:
An assembly is a compiled code library used for deployment, versioning, and security. It contains:
Manifest: Metadata about assembly (version, culture, references).
Type metadata: Classes, interfaces, enums, etc.
IL code: Intermediate Language code executed by CLR.
Types of Assemblies:
Private assembly – used by a single application.
Shared assembly – used by multiple apps, usually in GAC (Global Assembly Cache).
abstract class and interface?| Feature | Abstract Class | Interface |
|---|---|---|
| Inheritance | Single or multi-level | Multiple interfaces can be implemented |
| Members | Can have fields, constructors, methods | Only methods, properties, events (no fields) |
| Access Modifiers | Can be public, protected | All members are public by default |
| Implementation | Can have method implementation | Only from C# 8.0, default implementation allowed |
ref, out, and in parameters?ref: Passes variable by reference. Must be initialized before passing.
out: Passes variable by reference. No need to initialize before passing. Must be assigned in method.
in: Passes variable by reference but read-only inside method.
String and StringBuilder?| Feature | String | StringBuilder |
|---|---|---|
| Mutability | Immutable | Mutable |
| Performance | Slow for multiple changes | Fast for multiple modifications |
| Usage | For fixed strings | For dynamic/large string manipulations |
Answer:
Garbage Collection (GC) is the automatic memory management feature of CLR. It removes objects from memory that are no longer referenced, freeing up memory and preventing leaks.
Key Methods:
GC.Collect() – forces GC (use carefully).
Dispose() – releases unmanaged resources.
GC works on generations: 0 (new objects), 1 (short-lived), 2 (long-lived).
Thread and Task in .NET?Thread: Low-level unit of execution. You need to manage creation and destruction.
Task: Higher-level abstraction introduced in .NET 4.0 for async programming. Easier for thread pooling, async/await.
Answer:
A delegate is a type-safe function pointer that references methods with a specific signature.
Example:
public delegate void Notify(string message);
public class Program
{
static void SendMessage(string msg) { Console.WriteLine(msg); }
static void Main()
{
Notify notify = SendMessage;
notify("Hello from delegate!");
}
}
Multicast Delegate: Can reference multiple methods.
Func / Action / Predicate: Generic delegates provided by .NET.
== and Equals() for reference types?== checks reference equality (do both references point to the same object).
.Equals() can be overridden to check object content equality.
Array and ArrayList?| Feature | Array | ArrayList |
|---|---|---|
| Type | Strongly typed | Can store any type (object) |
| Size | Fixed | Dynamic |
| Performance | Faster | Slower due to boxing/unboxing |
| Namespace | System | System.Collections |
For generic type safety, prefer
List<T>overArrayList.
ViewState and Session in ASP.NET?| Feature | ViewState | Session |
|---|---|---|
| Storage | Page (hidden field) | Server |
| Lifetime | Page request | Across multiple pages/sessions |
| Size Limit | Small | Large |
| Security | Visible in page source | More secure |
Answer:
MVC stands for Model-View-Controller. It's a design pattern that separates an application into three parts:
Model: Represents the data and business logic.
View: Displays data to the user.
Controller: Handles user input and interactions.
Benefits:
Separation of concerns
Easier testing
Better maintainability
Q1: How will you handle exceptions in C#?
Answer: Use try-catch-finally blocks. Example:
try
{
int result = 10 / 0;
}
catch(DivideByZeroException ex)
{
Console.WriteLine(ex.Message);
}
finally
{
Console.WriteLine("Cleanup code.");
}
Q2: How will you make a class singleton?
Answer:
public class Singleton
{
private static Singleton instance = null;
private Singleton() { }
public static Singleton Instance
{
get
{
if(instance == null)
instance = new Singleton();
return instance;
}
}
}
Q3: Difference between Server.Transfer and Response.Redirect?
Server.Transfer – transfers request on server, no new request, faster.
Response.Redirect – sends HTTP redirect to browser, client makes new request.
Answer:
JIT (Just-In-Time) compilation converts MSIL (Microsoft Intermediate Language) to native code at runtime. Types:
Pre-JIT: Compiles entire code at once before execution.
Econo-JIT: Compiles only called methods; removes from memory when not needed.
Normal JIT: Compiles methods as they are called and keeps them for later use.
| Feature | Early Binding | Late Binding |
|---|---|---|
| Compilation | Compile-time | Runtime |
| Type Checking | Done at compile time | Done at runtime |
| Performance | Faster | Slower |
| Example | MyClass obj = new MyClass(); |
object obj = Activator.CreateInstance("MyClass"); |
Boxing: Converting a value type to a reference type.
Unboxing: Converting a reference type back to a value type.
Example:
int num = 123;
object obj = num; // Boxing
int x = (int)obj; // Unboxing
public: Accessible from anywhere
private: Accessible only within class
protected: Accessible within class and derived classes
internal: Accessible within the same assembly
protected internal: Accessible within same assembly or derived class
private protected: Accessible within same class or derived class in same assembly
override, new, and virtual?virtual: Allows a method to be overridden in a derived class.
override: Overrides a base class virtual method.
new: Hides a base class method without overriding.
Answer:
An event is a way for a class to notify other classes when something happens. Events are based on delegates.
public delegate void Notify();
public class Process
{
public event Notify ProcessCompleted;
public void Start() => ProcessCompleted?.Invoke();
}
Array and List<T>| Feature | Array | List |
|---|---|---|
| Size | Fixed | Dynamic |
| Type Safety | Yes | Yes (generic) |
| Methods | Limited | Rich set of methods (Add, Remove, Find) |
| Performance | Faster | Slightly slower due to dynamic resizing |
== and Equals() for reference types==: Compares references.
Equals(): Compares values or content, can be overridden.
IEnumerable and IQueryableIEnumerable: Executes query in memory, works with collections.
IQueryable: Executes query on data source, works with LINQ-to-SQL/Entities, supports deferred execution.
const and readonly in C#?| Feature | const | readonly |
|---|---|---|
| Initialization | Compile-time | Run-time (constructor allowed) |
| Value | Cannot change | Can assign once at runtime |
| Static | Always static | Not necessarily static |
Generics allow type-safe data structures and methods without knowing the type in advance.
List<int> numbers = new List<int>();
numbers.Add(10);
Benefits:
Type safety
Performance improvement (no boxing/unboxing)
Struct and Class?| Feature | Struct | Class |
|---|---|---|
| Type | Value type | Reference type |
| Inheritance | Cannot inherit | Can inherit |
| Memory | Stack | Heap |
| Constructor | No default constructor | Can have default constructor |
abstract class and interfaceAlready covered in first 20, but a refresher:
Abstract can have fields and constructors
Interface cannot have fields (before C# 8.0)
Classes can implement multiple interfaces but inherit only one abstract class
Partial class in C#?Allows splitting a class definition across multiple files.
Useful in auto-generated code scenarios (like Windows Forms).
partial class Employee { public void Display() {} }
partial class Employee { public void Show() {} }
Task and ThreadThread: Low-level, manual management, heavy.
Task: High-level, easier async programming, uses thread pool internally.
Server.Transfer and Response.RedirectServer.Transfer: Server-side transfer, faster, URL remains same.
Response.Redirect: Client-side redirect, new request, URL changes.
Session and Application in ASP.NET| Feature | Session | Application |
|---|---|---|
| Scope | Per user | Global |
| Storage | Server memory | Server memory |
| Life | User session | Application life |
| Usage | User-specific data | Shared data across users |
HashTable and Dictionary| Feature | HashTable | Dictionary |
|---|---|---|
| Type Safety | No (stores object) | Yes (generic) |
| Performance | Slower | Faster |
| Null Key/Value | Allows null key/value | Null key not allowed |
Answer:
LINQ (Language Integrated Query) allows querying collections in C# using SQL-like syntax.
var result = from emp in employees where emp.Age > 25 select emp;
Advantages:
Strongly typed
Compile-time checking
Can query arrays, lists, XML, DB
Answer:
ADO.NET is data access technology in .NET. It is used to connect, retrieve, manipulate, and update data from a database.
Key Objects:
Connection – Connect to DB
Command – Execute SQL commands
DataReader – Read data fast (forward-only)
DataSet – In-memory collection of data
DataSet and DataReader| Feature | DataSet | DataReader |
|---|---|---|
| Connection | Disconnected | Connected |
| Data Access | Multiple tables | Single table |
| Performance | Slower | Faster |
| Read/Write | Read/Write | Forward-only read |
ASP.NET Web Forms and MVC| Feature | Web Forms | MVC |
|---|---|---|
| Architecture | Event-driven | Model-View-Controller |
| Control | Server controls | HTML, JS, Razor |
| Testability | Low | High |
| URL | Not SEO-friendly | SEO-friendly |
ViewState: Stores page and control values between postbacks.
ControlState: Used by server controls to persist critical info, cannot be disabled like ViewState.
AppDomain and Process?Process: OS-level unit of execution.
AppDomain: Lightweight, isolated environment within a process where .NET apps run.
Finalize() and Dispose()Finalize(): Called by GC, cannot guarantee time, used for unmanaged resources.
Dispose(): Called manually, releases resources immediately.
async and await in C#?async: Marks method as asynchronous.
await: Waits for async operation without blocking thread.
async Task<int> GetDataAsync() { return await Task.Run(() => 10); }
Ref and Out parametersAlready discussed in first 20, but key points:
ref requires initialization before passing
out does not require initialization, must be assigned inside method
String and StringBuilderString: Immutable, slower for concatenation
StringBuilder: Mutable, faster for multiple modifications
public, private, protected, internal, protected internalAlready discussed, key refresher:
Determines visibility of members across class, assembly, and derived classes
ArrayList, List<T>, Dictionary<K,V>ArrayList: Non-generic, stores object, slower
List: Generic, faster, type-safe
Dictionary<K,V>: Key-value pair collection, fast lookup
Dependency Injection in .NET?Answer:
Dependency Injection (DI) is a design pattern where dependencies (objects) are injected into a class rather than created inside it.
Example in ASP.NET Core:
public class HomeController
{
private readonly IEmployeeService _service;
public HomeController(IEmployeeService service) { _service = service; }
}
Benefits:
Loosely coupled code
Easy to test
Maintainable
NuGet is a package manager for .NET.
Used to add third-party libraries or custom libraries to projects.
Attributes add metadata to classes, methods, properties.
Examples: [Serializable], [Obsolete], [WebMethod]
throw and throw exthrow: Preserves original stack trace
throw ex: Resets stack trace, not recommended
Task.Run and Task.Factory.StartNewTask.Run: Simple way to run task on thread pool
Task.Factory.StartNew: More configurable, used in advanced scenarios
Answer:
.NET is a software development framework developed by Microsoft that provides a controlled environment for developing and running applications. It includes a large class library called Framework Class Library (FCL) and a runtime environment called Common Language Runtime (CLR).
CLR: Manages memory, handles exceptions, and provides security.
FCL: Offers pre-built code for common tasks like file handling, data access, and XML manipulation.
Scenario Example:
If you’re developing a desktop application and a web API simultaneously, .NET allows you to use the same language (C#) and shared libraries across projects.
| Feature | .NET Framework | .NET Core | .NET 5/6/7 |
|---|---|---|---|
| Platform | Windows only | Cross-platform | Cross-platform |
| Performance | Moderate | High | Very High |
| Open Source | No | Yes | Yes |
| Supported Apps | Desktop, Web | Web, Cloud, Microservices | Web, Cloud, Microservices, Desktop |
| Versioning | Monolithic | Side-by-side versions | Unified platform |
Scenario:
For a microservices architecture hosted in Linux containers, .NET Core or .NET 6/7 is preferable over the .NET Framework.
Answer:
CLR (Common Language Runtime) is the execution engine for .NET applications. It provides services like:
Memory Management: Automatic garbage collection.
Type Safety: Ensures code uses data types safely.
Exception Handling: Standardized mechanism for exceptions.
Security: Code Access Security (CAS).
Flow of Execution:
C# code → Compiled into IL (Intermediate Language)
IL → JIT Compilation → Native code
CLR executes the native code.
Scenario Example:
When deploying a web API, CLR manages memory allocation for requests and automatically frees resources after execution, preventing memory leaks.
| Type | Storage | Lifetime | Example |
|---|---|---|---|
| Value Types | Stack | Short-lived | int, double, struct |
| Reference Types | Heap | Long-lived | class, array, string |
Value types hold the actual data.
Reference types hold a reference to the data in memory.
Scenario:
For a method that processes numbers, using value types (like int) is more efficient than reference types because they avoid heap allocation.
Answer:
Garbage Collection (GC) is the process of automatically releasing memory occupied by objects that are no longer in use.
Generations:
Gen 0: Short-lived objects (temporary)
Gen 1: Medium-lived objects
Gen 2: Long-lived objects (like static objects)
Scenario Example:
When creating many temporary objects in a loop (like processing files), GC cleans up Gen 0 objects quickly without affecting performance.
IEnumerable and IQueryable| Feature | IEnumerable | IQueryable |
|---|---|---|
| Execution | In-memory (client-side) | Database-side (deferred) |
| Namespace | System.Collections | System.Linq |
| Query Provider | LINQ to Objects | LINQ to SQL / EF |
| Performance | Slower for large data sets | Faster for large datasets |
Scenario:
Use IQueryable when fetching filtered data from a database to reduce memory load. IEnumerable is suitable for in-memory collections.
abstract class and interface| Feature | Abstract Class | Interface |
|---|---|---|
| Multiple Inheritance | No | Yes |
| Members | Methods, properties, fields | Only method/property signatures (C# 8.0 supports default methods) |
| Constructor | Allowed | Not allowed |
| Usage | Base class with common code | Contract to implement |
Scenario Example:
Use an abstract class for common functionalities (e.g., Vehicle) and interfaces for capabilities (e.g., IFlyable, IDrivable).
Answer:
MVC stands for Model-View-Controller, a design pattern that separates application into:
Model: Business logic and data access
View: UI layer
Controller: Handles user requests and coordinates model and view
Advantages:
Separation of concerns
Testable and maintainable code
Supports RESTful URLs
Better control over HTML and JavaScript
Scenario Example:
In an e-commerce app, controllers handle requests for products, models fetch data from the database, and views display it dynamically to users.
Answer:
Entity Framework is an ORM (Object Relational Mapper) for .NET that allows developers to interact with databases using C# objects instead of SQL.
Types of EF:
Database-First: Generates models from an existing database.
Model-First: Create models first, then generate database.
Code-First: Write code first, EF generates the database schema.
Scenario Example:
For a new project, Code-First EF allows you to define classes and automatically create tables in SQL Server.
Answer:
Web API is a framework for building HTTP-based services that can be consumed by browsers, mobile devices, and desktop applications.
Supports RESTful services
Can return data in JSON or XML
Lightweight compared to WCF
Scenario Example:
Creating an API to fetch product details for both a website and mobile app ensures code reuse.
async/await and synchronous calls| Feature | Synchronous | Asynchronous (async/await) |
|---|---|---|
| Execution | Blocks the calling thread | Non-blocking |
| Performance | Slower for I/O operations | Faster, efficient |
| Resource Usage | High thread usage | Low thread usage |
Scenario Example:
Fetching data from a third-party API in an ASP.NET Core application should use async/await to keep the server responsive.
Answer:
Dependency Injection (DI) is a design pattern that injects dependencies into a class rather than the class creating them.
Types:
Constructor Injection
Property Injection
Method Injection
Scenario Example:
In ASP.NET Core, injecting a logging service into a controller ensures loose coupling and easier testing.
Dispose() and Finalize()| Feature | Dispose() | Finalize() |
|---|---|---|
| Purpose | Release unmanaged resources early | Cleanup before garbage collection |
| Call | Explicitly called | Called by GC automatically |
| Implementation | IDisposable interface | Override Finalize() method |
Scenario Example:
Dispose database connections immediately after use rather than waiting for GC to call Finalize.
Delegate:
A type-safe pointer to a method.
Event:
A wrapper around a delegate that allows subscribers to be notified when something happens.
Scenario Example:
Delegate: Pass a method as a parameter for sorting.
Event: Notify UI when data processing completes.
Singleton: One instance for global access
Factory: Creates objects without exposing instantiation
Repository: Encapsulates data access logic
Unit of Work: Manages transactions for multiple repositories
Decorator / Strategy: Add behavior dynamically
Scenario Example:
Use the Repository pattern with Entity Framework to abstract data access logic from business logic.
Task and Thread| Feature | Thread | Task |
|---|---|---|
| Usage | Low-level threading | High-level abstraction |
| Lifecycle | Managed manually | Managed by Task Scheduler |
| Result | Void or return value | Supports return and continuations |
Scenario Example:
Use Task.Run() for asynchronous operations instead of manually managing threads.
Answer:
Middleware is a pipeline component that handles HTTP requests and responses. Examples:
Authentication
Logging
Exception Handling
CORS
Scenario Example:
You can add custom middleware to log request and response details for debugging purposes.
Answer:
Blazor is a framework for building interactive web UIs using C# instead of JavaScript.
Server-side Blazor: Code runs on the server
WebAssembly Blazor: Code runs in the browser
Scenario Example:
A dashboard app can use Blazor to run real-time updates in the browser without relying on JavaScript frameworks.
Answer:
.NET uses strong naming to uniquely identify assemblies with:
Name
Version
Culture
Public Key Token
Scenario Example:
Side-by-side execution allows two apps to use different versions of the same library without conflict.
Use async/await for I/O
Avoid unnecessary boxing/unboxing
Use StringBuilder for string concatenation
Optimize LINQ queries
Enable caching for expensive operations
Use compiled regular expressions
Profile and monitor memory usage
Scenario Example:
For a high-traffic API, caching frequently accessed data reduces database load and improves response time.
| Feature | Web Forms | MVC |
|---|---|---|
| Architecture | Event-driven, page-centric | Model-View-Controller |
| State Management | ViewState used for storing state | Stateless by default, uses TempData/Session |
| Control | Server controls (heavyweight) | HTML helpers & Razor views |
| Testability | Difficult | High testability |
| URL Routing | Poor SEO-friendly URLs | RESTful, SEO-friendly URLs |
| Performance | Slower for large applications | Faster due to lightweight pages |
Scenario:
For a modern web application with REST APIs and responsive design, MVC or ASP.NET Core MVC is preferred over Web Forms.
Answer:
The middleware pipeline is a sequence of components that process incoming HTTP requests and generate responses. Middleware can:
Modify requests
Short-circuit requests
Call the next middleware
Common built-in middleware:
UseRouting()
UseAuthentication()
UseAuthorization()
UseEndpoints()
UseStaticFiles()
Scenario:
A custom logging middleware can record request start time, invoke next(), then log response time to monitor performance.
IActionResult and ActionResult<T> in ASP.NET Core| Feature | IActionResult | ActionResult |
|---|---|---|
| Type Safety | Not type-safe | Type-safe |
| Return Type | Can return any result (Ok, NotFound) | Returns specific type or IActionResult |
| Use Case | General actions | Strongly typed API responses |
Scenario:
For Web API endpoints returning JSON, ActionResult<Product> ensures compile-time type safety while allowing HTTP status codes.
Answer:
Routing maps incoming HTTP requests to controller actions or endpoints.
Types:
Convention-based routing: Defined in Startup.cs
Attribute-based routing: [Route("api/products/{id}")] on controller/actions
Scenario:
Attribute routing is preferred for APIs because it allows clear, RESTful paths and versioning, e.g., /api/v1/products.
Answer:
ASP.NET Core has built-in DI for injecting services into controllers or other classes.
Service Lifetimes:
Transient: New instance every request (services.AddTransient<>)
Scoped: One instance per request (services.AddScoped<>)
Singleton: One instance for application lifetime (services.AddSingleton<>)
Scenario:
Use Scoped for DbContext in EF Core to ensure one context per HTTP request.
Include and ThenInclude in EF CoreInclude: Fetch related entity (single-level)
ThenInclude: Fetch nested/child entities (multi-level)
Example:
var orders = context.Customers
.Include(c => c.Orders)
.ThenInclude(o => o.OrderDetails)
.ToList();
Scenario:
For a reporting API, eager loading using Include/ThenInclude reduces multiple database trips and improves performance.
| Feature | Lazy Loading | Eager Loading |
|---|---|---|
| When Data Loads | On-demand when accessed | Immediately with main query |
| Performance | May cause multiple DB calls | Fewer DB calls |
| Syntax | Virtual navigation property | Use Include() |
Scenario:
Lazy loading is fine for small datasets, but for APIs returning multiple records with related data, eager loading is recommended to avoid N+1 query issues.
Answer:
ASP.NET Core provides built-in logging via ILogger<T>.
Steps:
Inject ILogger<T> in constructor.
Use LogInformation, LogWarning, LogError.
private readonly ILogger<ProductController> _logger;
public ProductController(ILogger<ProductController> logger)
{
_logger = logger;
}
public IActionResult Get()
{
_logger.LogInformation("Fetching products");
return Ok(_context.Products.ToList());
}
Scenario:
Logging helps track errors, monitor API performance, and troubleshoot production issues without stopping the app.
IHostedService and Background Services in ASP.NET CoreIHostedService: Interface for background tasks
BackgroundService: Base class for long-running services
Use Case: Email notifications, scheduled tasks, queue processing
public class EmailService : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
// Process email queue
await Task.Delay(5000, stoppingToken);
}
}
}
Scenario:
Used for sending batch notifications without blocking HTTP requests.
appsettings.json and User Secrets| Feature | appsettings.json | User Secrets |
|---|---|---|
| Purpose | General configuration | Store sensitive secrets |
| Environment-Specific | Supported via appsettings.Development.json | N/A |
| Security | Checked into source control | Not checked into source control |
Scenario:
Use User Secrets in development to store API keys without exposing them in source control.
Authentication: IdentityServer, JWT tokens, OAuth2
Authorization: Role-based or policy-based
HTTPS: Enforce HTTPS redirection
CORS: Allow only trusted origins
Data Protection: Encrypt sensitive data
Scenario:
For a banking API, JWT tokens with short expiry and refresh tokens ensure secure access to customer data.
async/await deadlocks in ASP.NET CoreProblem:
Using .Result or .Wait() on async tasks can block the thread, causing deadlocks.
Solution:
Use await all the way
Avoid synchronous blocking in async methods
public async Task<IActionResult> Get()
{
var data = await _service.GetProductsAsync();
return Ok(data);
}
Scenario:
When calling external APIs asynchronously, always await to prevent thread pool exhaustion in production.
ValueTask and TaskTask: Always allocates a heap object
ValueTask: Avoids heap allocation for completed tasks
Scenario:
Use ValueTask for high-performance APIs where methods often complete synchronously.
In-Memory Cache: For single-server apps
Distributed Cache: Redis or SQL Server for multi-server apps
Response Caching: Cache entire HTTP responses
Output Caching: For static API responses
Scenario:
Caching popular product data reduces database hits and improves API performance.
gRPC: High-performance, strongly-typed RPC framework
Use Case: Microservices communication, streaming, low-latency APIs
Advantage: Faster than REST for internal services
Scenario:
Use gRPC for a high-frequency trading system between services requiring minimal latency.
lock, Mutex, and Semaphore in .NET| Feature | lock (Monitor) |
Mutex | Semaphore |
|---|---|---|---|
| Scope | Thread within process | Thread across processes | Controls access for multiple threads |
| Overhead | Low | High | Medium |
| Usage | Critical sections | Cross-process synchronization | Limit concurrent threads |
Scenario Example:
lock for simple thread-safe operations in memory.
Mutex when multiple processes need exclusive access to a shared resource.
Semaphore to limit concurrent API calls to an external service.
async and await with a real-time scenarioAnswer:
async marks a method as asynchronous. await pauses execution until the task completes without blocking the thread.
Example:
public async Task<IActionResult> GetProductsAsync()
{
var products = await _productService.FetchFromDatabaseAsync();
return Ok(products);
}
Scenario:
In a web API fetching data from multiple databases, using async/await prevents thread blocking, allowing high throughput.
CancellationToken and IProgress?CancellationToken: Allows cancellation of long-running tasks.
IProgress: Reports progress from a background task to UI or caller.
Example:
public async Task ProcessDataAsync(CancellationToken token, IProgress<int> progress)
{
for (int i = 0; i < 100; i++)
{
token.ThrowIfCancellationRequested();
progress.Report(i);
await Task.Delay(100);
}
}
Scenario:
Used in background services or batch processing tasks in APIs, allowing users to cancel tasks gracefully.
ThreadPool vs TaskThreadPool: Pre-created threads for short-lived tasks.
Task: Higher-level abstraction over threads; can be scheduled on the thread pool.
Scenario:
Use Task.Run() instead of creating new threads manually to improve scalability of background operations.
Causes:
Multiple threads waiting for each other to release resources.
Blocking async code (.Result or .Wait()).
Solutions:
Avoid nested locks.
Use async/await properly.
Use Monitor.TryEnter with timeout.
Scenario:
Deadlocks often occur in web apps when async DB calls are blocked by .Result. Switching to fully asynchronous methods fixes the issue.
MemoryCache vs DistributedCache| Feature | MemoryCache | DistributedCache |
|---|---|---|
| Scope | Single server | Multiple servers |
| Storage | In-memory | Redis, SQL Server, NCache |
| Use Case | Temporary caching for a server | Shared caching across services |
Scenario:
Use DistributedCache for caching product catalog in a cloud microservices environment to avoid repeated DB hits.
Answer:
Microservices is an architectural style where each service handles a single business capability.
Implementation in .NET:
Use ASP.NET Core Web API for services.
Docker for containerization.
gRPC or REST for communication.
Event Bus (RabbitMQ/Kafka) for asynchronous communication.
Health checks with IHealthCheck.
Scenario:
E-commerce app with separate services for Products, Orders, Payments, and Inventory.
Query String Versioning: /api/products?version=1.0
URL Path Versioning: /api/v1/products
Header Versioning: X-API-Version: 1.0
Media Type Versioning: Accept: application/vnd.myapi.v1+json
Scenario:
URL path versioning is most common for REST APIs to maintain backward compatibility.
JWT and OAuth2| Feature | JWT (JSON Web Token) | OAuth2 |
|---|---|---|
| Purpose | Token format for authentication | Authorization framework |
| Usage | Stateless token | Access delegation |
| Expiry | Embedded in token | Can issue refresh tokens |
Scenario:
Use JWT for stateless authentication in a REST API and OAuth2 for third-party login (Google/Facebook).
gRPC: High-performance RPC protocol with binary serialization.
Advantages:
Faster than JSON/REST
Strongly-typed contracts
Supports streaming
Scenario:
Use gRPC for internal microservices requiring high throughput, e.g., real-time financial data streaming.
IDisposable and using in .NETIDisposable: Interface to free unmanaged resources.
using statement: Automatically calls Dispose after scope ends.
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
// Use connection
}
Scenario:
Always dispose DbContext or FileStream to prevent memory leaks in APIs.
Span<T> and Memory<T> in .NET?Span: Stack-only, efficient for slices of arrays.
Memory: Heap-allocated, can be async-friendly.
Scenario:
For high-performance string or array manipulations in APIs without heap allocations.
ValueTask vs TaskTask: Always allocates an object on heap.
ValueTask: Avoids heap allocation if method completes synchronously.
Scenario:
Use ValueTask in high-performance APIs that often complete immediately.
SignalR: Real-time communication library.
Use Case: Chat apps, dashboards, notifications.
Scenario:
A stock trading app can use SignalR to update stock prices live on the client UI.
Profile with dotTrace, ANTS, or PerfView
Optimize LINQ queries and reduce N+1 problem
Cache frequently accessed data
Use async/await for I/O-bound tasks
Minimize boxing/unboxing
Use Span<T> and Memory<T> for large arrays
Reduce memory allocations and dispose objects properly
Enable response compression for APIs
Scenario:
For high-load web APIs, combining caching, async calls, and optimized queries improves throughput drastically.