.NET

.NET

Top Interview Questions

About .NET

 

Introduction to .NET

.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.


History of .NET

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:

  1. .NET Framework (2002): The original version, primarily for Windows desktop and server applications. It included languages like C#, VB.NET, and F#.

  2. .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.

  3. .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.


Key Features of .NET

.NET has several features that make it a preferred choice for enterprise and modern application development:

1. Cross-Platform Support

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.

2. Multiple Language Support

.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.

3. Unified Programming Model

.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.

4. High Performance

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.

5. Security

.NET offers built-in security features such as code access security, role-based security, encryption, and authentication mechanisms to protect applications from unauthorized access.

6. Scalability

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.

7. Rich IDE Support

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.


Architecture of .NET

.NET is built on a layered architecture that simplifies application development and deployment:

1. Common Language Runtime (CLR)

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).

2. Base Class Library (BCL)

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.

3. Application Models

.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.


Types of .NET Applications

.NET allows developers to create a variety of applications:

1. Web 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.

2. Desktop Applications

WinForms and WPF enable developers to create rich desktop applications for Windows with interactive UIs, multimedia support, and robust event-driven programming.

3. Mobile Applications

.NET MAUI (Multi-platform App UI) and Xamarin allow building native mobile apps for iOS and Android using a single codebase.

4. Cloud Applications

.NET integrates seamlessly with Microsoft Azure and other cloud services for scalable, distributed applications. Features like microservices, serverless computing, and containerization are fully supported.

5. Gaming Applications

.NET supports game development with libraries like MonoGame and Unity (C# scripting), enabling cross-platform gaming experiences.

6. IoT and Embedded Systems

With .NET IoT libraries, developers can build applications for sensors, devices, and embedded systems.


.NET in Modern Development

1. Microservices Architecture

.NET Core and later versions are ideal for building microservices due to modularity, lightweight containers, and cross-platform deployment.

2. Cloud-Native Development

.NET integrates with Azure DevOps, Kubernetes, Docker, and CI/CD pipelines for cloud-native solutions.

3. AI and Machine Learning

.NET provides ML.NET for machine learning, allowing developers to train, evaluate, and deploy models using C# and F#.

4. Cross-Platform Web Apps

Blazor allows building full-stack web apps with C# instead of JavaScript, making it easier for .NET developers to create interactive front-end applications.


Advantages of Using .NET

  • 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.

 

Fresher Interview Questions

 

1. What is .NET?

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.


2. What is the difference between .NET Framework and .NET Core?

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.


3. What is CLR (Common Language Runtime)?

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.


4. What is the difference between Managed and Unmanaged code?

  • 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.


5. What is CTS (Common Type System)?

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.


6. What is the difference between Stack and Heap memory?

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.


7. What is the difference between value types and reference types?

  • 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.


8. What is the difference between == 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

9. What are assemblies in .NET?

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:

  1. Private assembly – used by a single application.

  2. Shared assembly – used by multiple apps, usually in GAC (Global Assembly Cache).


10. What is the difference between 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

11. What is the difference between 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.


12. What is the difference between 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

13. What is Garbage Collection in .NET?

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).


14. What is the difference between 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.


15. What are delegates in C#?

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.


16. What is the difference between == 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.


17. What is the difference between 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> over ArrayList.


18. What is the difference between 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

19. What is MVC in ASP.NET?

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


20. Common scenario-based questions for freshers:

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.


21. What are the types of JIT compilation in .NET?

Answer:
JIT (Just-In-Time) compilation converts MSIL (Microsoft Intermediate Language) to native code at runtime. Types:

  1. Pre-JIT: Compiles entire code at once before execution.

  2. Econo-JIT: Compiles only called methods; removes from memory when not needed.

  3. Normal JIT: Compiles methods as they are called and keeps them for later use.


22. What is the difference between early binding and late binding?

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");

23. What is boxing and unboxing in C#?

  • 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

24. What are the access modifiers in C#?

  • 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


25. What is the difference between 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.


26. What are events in C#?

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();
}

27. Difference between 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

28. Difference between == and Equals() for reference types

  • ==: Compares references.

  • Equals(): Compares values or content, can be overridden.


29. Difference between IEnumerable and IQueryable

  • IEnumerable: Executes query in memory, works with collections.

  • IQueryable: Executes query on data source, works with LINQ-to-SQL/Entities, supports deferred execution.


30. What is the difference between 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

31. What are generics in C#?

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)


32. What are the differences between 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

33. Difference between abstract class and interface

Already 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


34. What is 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() {} }

35. Difference between Task and Thread

  • Thread: Low-level, manual management, heavy.

  • Task: High-level, easier async programming, uses thread pool internally.


36. Difference between Server.Transfer and Response.Redirect

  • Server.Transfer: Server-side transfer, faster, URL remains same.

  • Response.Redirect: Client-side redirect, new request, URL changes.


37. Difference between 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

38. Difference between 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

39. What is LINQ?

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


40. What is ADO.NET?

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


41. Difference between 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

42. Difference between 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

43. What are ViewState and ControlState in ASP.NET?

  • ViewState: Stores page and control values between postbacks.

  • ControlState: Used by server controls to persist critical info, cannot be disabled like ViewState.


44. What is the difference between AppDomain and Process?

  • Process: OS-level unit of execution.

  • AppDomain: Lightweight, isolated environment within a process where .NET apps run.


45. Difference between Finalize() and Dispose()

  • Finalize(): Called by GC, cannot guarantee time, used for unmanaged resources.

  • Dispose(): Called manually, releases resources immediately.


46. What is 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); }

47. Difference between Ref and Out parameters

Already discussed in first 20, but key points:

  • ref requires initialization before passing

  • out does not require initialization, must be assigned inside method


48. Difference between String and StringBuilder

  • String: Immutable, slower for concatenation

  • StringBuilder: Mutable, faster for multiple modifications


49. Difference between public, private, protected, internal, protected internal

Already discussed, key refresher:

  • Determines visibility of members across class, assembly, and derived classes


50. What are the differences between 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


51. What is 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


52. What are NuGet packages?

  • NuGet is a package manager for .NET.

  • Used to add third-party libraries or custom libraries to projects.


53. What are Attributes in C#?

  • Attributes add metadata to classes, methods, properties.

  • Examples: [Serializable], [Obsolete], [WebMethod]


54. Difference between throw and throw ex

  • throw: Preserves original stack trace

  • throw ex: Resets stack trace, not recommended


55. Difference between Task.Run and Task.Factory.StartNew

  • Task.Run: Simple way to run task on thread pool

  • Task.Factory.StartNew: More configurable, used in advanced scenarios

 

Experienced Interview Questions

 

1. What is .NET?

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.


2. What is the difference between .NET Framework, .NET Core, and .NET 5/6/7?

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.


3. What is CLR and how does it work?

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:

  1. C# code → Compiled into IL (Intermediate Language)

  2. IL → JIT Compilation → Native code

  3. 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.


4. What are value types and reference types in C#?

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.


5. Explain Garbage Collection in .NET

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.


6. Difference between 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.


7. Difference between 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).


8. What is ASP.NET MVC and its advantages?

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.


9. Explain Entity Framework (EF) and its types

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:

  1. Database-First: Generates models from an existing database.

  2. Model-First: Create models first, then generate database.

  3. 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.


10. What is Web API in .NET?

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.


11. Difference between 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.


12. Explain Dependency Injection in .NET

Answer:
Dependency Injection (DI) is a design pattern that injects dependencies into a class rather than the class creating them.

Types:

  1. Constructor Injection

  2. Property Injection

  3. Method Injection

Scenario Example:
In ASP.NET Core, injecting a logging service into a controller ensures loose coupling and easier testing.


13. Difference between 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.


14. What are Delegates and Events?

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.


15. What are design patterns commonly used in .NET?

  • 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.


16. Difference between 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.


17. Explain Middleware in ASP.NET Core

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.


18. What is Blazor in .NET?

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.


19. How does .NET handle versioning of assemblies?

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.


20. Common performance optimization techniques in .NET

  • 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.


21. What are the differences between ASP.NET Web Forms and ASP.NET MVC?

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.


22. Explain ASP.NET Core Middleware Pipeline

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.


23. Difference between 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.


24. Explain Routing in ASP.NET Core

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.


25. What is Dependency Injection in ASP.NET Core and its lifetimes?

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.


26. Difference between Include and ThenInclude in EF Core

  • Include: 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.


27. What is Lazy Loading vs Eager Loading in EF Core?

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.


28. How to implement logging in ASP.NET Core?

Answer:
ASP.NET Core provides built-in logging via ILogger<T>.

Steps:

  1. Inject ILogger<T> in constructor.

  2. 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.


29. Explain IHostedService and Background Services in ASP.NET Core

  • IHostedService: 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.


30. Difference between 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.


31. How to secure ASP.NET Core Web API?

  • 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.


32. Explain async/await deadlocks in ASP.NET Core

Problem:
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.


33. Difference between ValueTask and Task

  • Task: Always allocates a heap object

  • ValueTask: Avoids heap allocation for completed tasks

Scenario:
Use ValueTask for high-performance APIs where methods often complete synchronously.


34. Explain Caching strategies in .NET Core

  1. In-Memory Cache: For single-server apps

  2. Distributed Cache: Redis or SQL Server for multi-server apps

  3. Response Caching: Cache entire HTTP responses

  4. Output Caching: For static API responses

Scenario:
Caching popular product data reduces database hits and improves API performance.


35. What is gRPC and when to use it in .NET?

  • 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.


36. Explain the difference between 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.


37. Explain async and await with a real-time scenario

Answer:
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.


38. What are 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.


39. Explain ThreadPool vs Task

  • ThreadPool: 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.


40. How to handle deadlocks in .NET?

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.


41. Explain 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.


42. What are Microservices and how are they implemented in .NET?

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.


43. How do you handle versioning in Web APIs?

  • 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.


44. Difference between 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).


45. What is gRPC and why choose it over REST?

  • 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.


46. Explain IDisposable and using in .NET

  • IDisposable: 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.


47. What is 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.


48. Explain ValueTask vs Task

  • Task: 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.


49. What is SignalR in .NET?

  • 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.


50. How to perform performance tuning in .NET applications?

  1. Profile with dotTrace, ANTS, or PerfView

  2. Optimize LINQ queries and reduce N+1 problem

  3. Cache frequently accessed data

  4. Use async/await for I/O-bound tasks

  5. Minimize boxing/unboxing

  6. Use Span<T> and Memory<T> for large arrays

  7. Reduce memory allocations and dispose objects properly

  8. Enable response compression for APIs

Scenario:
For high-load web APIs, combining caching, async calls, and optimized queries improves throughput drastically.