Dot Net Interview Questions
Dot Net Interview Questions
NET and C#
Feature .NET C#
Definition .NET is a framework for building applications. C# is a programming language used to
It provides runtime, libraries, and tools for develop applications on the .NET
development. platform.
Type It is a platform that supports multiple languages It is an object-oriented programming
(C#, VB.NET, F#, etc.). language created by Microsoft.
Role Provides an environment to execute and manage Used to write code that runs on the .NET
applications. framework or .NET Core.
Components Includes CLR (Common Language Runtime), Has features like LINQ, async/await,
libraries, ASP.NET, WinForms, and WPF. delegates, and more.
Example .NET enables web, desktop, mobile, and cloud C# is used to write logic inside a .NET-
application development. based application.
Summary
• .NET is a framework/platform, while C# is a language that runs on it.
• Think of .NET as an engine and C# as the fuel that powers applications.
1. Type Consistency Across Languages – Ensures that C#, VB.NET, and F# use the same data types.
2. Supports Language Interoperability – Allows multiple .NET languages to work together.
3. Provides Type Safety – Prevents invalid type conversions and memory issues.
• Value Types (Stored in the stack) – int, float, bool, char, struct, enum.
• Reference Types (Stored in the heap) – class, interface, delegate, array.
CTS ensures that an int in C# is treated the same as an Integer in VB.NET, making cross-language compatibility
possible.
The Common Language Specification (CLS) is a subset of CTS that defines a set of rules all .NET
languages must follow to ensure interoperability.
1. No Case Sensitivity Dependence – public void Print() and public void print() must not exist in the same
class.
2. Only Public Features Matter – Private/internal members are not part of CLS compliance.
3. Use Standard Data Types – Avoid unsigned integers (uint, ulong) since some languages don’t support
them.
1. Performance Overhead – Boxing involves memory allocation in the heap, making it slow.
2. Extra GC Pressure – More boxed objects lead to frequent garbage collection.
3. Explicit Casting Required – Unboxing needs explicit type casting, which can cause runtime errors.
4. Use var or Generics – Avoid unnecessary boxing/unboxing by using generics (List<int> instead of
List<object>).
Casting in .NET
char → int
1. Data Loss – When converting double → int, fractional parts are lost.
double pi = 3.14159;
int val = (int)pi; // Output: 3 (fraction lost)
2. Overflow or Underflow – Large values might not fit in the target type.
int large = 300;
byte small = (byte)large; // Output: 44 (data corruption)
Conclusion
Question 24: Difference Between Threads and Task Parallel Library (TPL)?
A Task in C# represents an asynchronous operation that runs in the background without blocking the
main thread. It is part of the Task Parallel Library (TPL) and is used for concurrent and parallel
programming
The out keyword in C# is used to pass arguments by reference, allowing a method to return multiple values.
Use Case: Returning multiple values from a method without using a class or struct.
An event in C# is a special delegate that is used to notify other parts of a program when something
happens (e.g., a button click).
Use Case: Events are used in GUI applications, logging systems, and event-driven architectures.
Use Case: Use interfaces when you only need method contracts without implementation.
class Program
{
// Step 1: Declare a delegate
delegate void MyDelegate(string message);
class EventExample
{
public delegate void NotifyHandler(string message);
public event NotifyHandler OnNotify; // Event declaration
class Program
{
static void ShowNotification(string msg)
{
Console.WriteLine(msg);
}
Summary
Delegate → Function pointer, used for callbacks.
Multicast Delegate → Holds multiple method references.
Event → A controlled way to use delegates for notifications.
Event vs Delegate → Events are more restricted and cannot be invoked directly.
Key Takeaway:
✔ Allows custom behavior for operators.
✔ Improves readability (c1 + c2 is better than Add(c1, c2)).
✔ Cannot overload =, &&, ||, new, typeof, etc.
Question 52: Why use a simple base class instead of an abstract class?
A simple base class is used when:
✔ You don’t need to force child classes to implement specific methods.
✔ You want to provide a default implementation that subclasses can inherit.
When to use an abstract class?
✔ If you want to enforce method overriding.
✔ If the base class should never be instantiated.
✔ If method overriding is not required, use a normal class instead of abstract.
public Example()
{
Console.WriteLine("Constructor executed");
}
int Initialize()
{
Console.WriteLine("Initializer executed");
return 10;
}
}
Question 75: What are Nested Classes and when to use them?
✔ A nested class is a class defined inside another class.
When to use Nested Classes?
1⃣ Encapsulation: When a class is only useful inside another class.
2⃣ Logical grouping: When a class is closely related to the outer class.
3⃣ Encapsulation of helper classes inside a main class.
Key Takeaway: Use nested classes only when the inner class is strongly related to the outer class.
Key Takeaway: Use inheritance and interfaces to extend functionality without modifying existing code.
Question 87: Explain Liskov Substitution Principle (LSP) and Its Violation?
✔ Definition:
A child class should be substitutable for its parent without breaking functionality.
If a subclass cannot completely replace its parent, it violates LSP.
Question 88: How to Fix LSP Violations?
✔ Solution: Use a Better Hierarchy
Question 90: Is there a connection between Liskov Substitution Principle (LSP) and Interface
Segregation Principle (ISP)?
✔ Yes! LSP and ISP are related because both ensure that classes follow proper hierarchy and behavior.
Connection:
High-level modules should not depend on low-level modules. Both should depend on abstractions.
Abstractions should not depend on details. Details should depend on abstractions.
csharp
Copy
Edit
class DataService
{
private readonly IDatabase _database;
Concept Type
SOLID Design Principles
IoC Architectural Pattern
DI Design Pattern
Key Takeaway:
Key Takeaway: SOLID is important, but not the only principle for good software architecture.
class Car
{
private readonly Engine _engine; // Strong dependency
class Program
{
static void UpdateValue(ref int number)
{
number += 10; // Changes the original value
}
ref vs out vs in
Keyword Initialization Required? Can Modify? Purpose
ref Yes (Must be initialized) Yes Passes a variable by reference
out No (Can be uninitialized) Yes Used to return multiple values
in Yes No (Read-only) Passes large structs efficiently
Question 119: What Effect Does Boxing and Unboxing Have on Performance?
✔ Performance impact:
1. Memory Overhead → Heap allocation increases memory usage.
2. CPU Overhead → Conversions between stack and heap slow down execution.
3. Garbage Collection → Frequent heap allocations lead to more garbage collection cycles.
Example – Performance Issue
✔ Avoid unnecessary boxing/unboxing to optimize performance.
Question 121: How Many Stacks and Heaps Are Created for an Application?
✔ Stack: One stack per thread (each thread gets its own stack).
✔ Heap: Only one heap per application (shared by all threads).
✔ Multiple stacks, but only one heap.
Question 147: Can .NET Apps Have Memory Leaks Despite GC?
✔ Yes! If objects are referenced indefinitely.
private Singleton() { }
Question 163: Is DAL (Data Access Layer) and Repository the same?
No, but they are related.
• DAL is a broader layer responsible for all database-related operations. It may include raw SQL queries,
stored procedures, and ORM usage.
• Repository Pattern is a design pattern within the DAL that abstracts the data operations and provides a
consistent API to the business logic.
The Repository Pattern is part of the DAL, but DAL is not always implemented using repositories.
Question 168: Do we need the Repository Pattern when EF Core already provides similar functionality?
Not always! EF Core already acts as a repository + unit of work, so in simple projects, an extra repository layer
might be unnecessary.
Use Repository Pattern if:
• You need decoupling between business logic and EF Core.
• You plan to switch databases in the future.
• You require complex queries that should not be tightly coupled with EF.
Don’t use it if:
• You only perform simple CRUD operations.
• You fully commit to EF Core without switching ORMs.
Question 170: How does the Repository Pattern make unit testing easy?
Because repositories abstract the data layer, we can:
Mock database operations (e.g., using Moq in C# or Mockito in Java).
Test business logic independently from the database.
Avoid slow integration tests when only unit testing is required.
Without repositories, you would need real database connections, making testing slower and more complex.
Question 171: How can we do mock testing with Repository?
Mock testing with repositories allows us to test business logic without interacting with a real database.
Steps to mock a repository:
1. Use a mocking framework like Moq (C#), Mockito (Java), or unittest.mock (Python).
2. Mock repository methods to return predefined data.
3. Inject the mock repository into the service being tested.
Example in C# using Moq
csharp
CopyEdit
var mockRepo = new Mock<IRepository<Product>>();
mockRepo.Setup(repo => repo.GetByIdAsync(1)).ReturnsAsync(new Product { Id = 1, Name = "Laptop" });
Question 172: What is the Factory Pattern and how does it benefit?
The Factory Pattern is a creational design pattern that provides an interface for creating objects, hiding the
instantiation logic from the client.
Benefits:
Centralizes object creation
Promotes loose coupling
Improves maintainability
Example in Java
java
CopyEdit
class VehicleFactory {
public static Vehicle getVehicle(String type) {
return switch (type) {
case "Car" -> new Car();
case "Bike" -> new Bike();
default -> throw new IllegalArgumentException("Unknown type");
};
}
}
Usage:
java
CopyEdit
Vehicle car = VehicleFactory.getVehicle("Car"); // No need to use `new`
No need to modify client code when adding new vehicle types!
Question 173: How does centralizing object creation help in loose coupling?
When object creation is centralized (e.g., using a Factory Pattern or Dependency Injection), the client code
does not depend on concrete implementations, making it easier to modify and test.
Without centralization (Tightly Coupled Code)
java
CopyEdit
Service service = new ServiceImpl(); // Hardcoded instantiation
With centralization (Loosely Coupled Code)
java
CopyEdit
Service service = ServiceFactory.getService(); // Factory handles creation
Flexible and testable
Easier to swap implementations
Question 179: Can’t we use a simple class instead of an interface for DI?
You can, but using interfaces is a best practice because:
Flexibility – Easily switch implementations
Testability – Mock dependencies in unit tests
Loose Coupling – Reduces dependency on concrete classes
Using a simple class (instead of an interface) can lead to:
• Tightly coupled code
• Harder testing (no easy way to mock dependencies)
• Difficult future changes
Use interfaces unless there is a compelling reason not to!
Question 181: So, if you just centralize object creation, is it the Factory Pattern?
Not necessarily.
Centralizing object creation is a key concept of the Factory Pattern, but just doing that alone does not make it
a Factory Pattern.
Factory Pattern involves:
Encapsulation of object creation logic
Returning objects of a common type (interface or superclass)
Loose coupling (client code doesn’t depend on specific classes)
Example (Factory Pattern):
java
CopyEdit
class ServiceFactory {
public static Service getService(String type) {
return switch (type) {
case "A" -> new ServiceA();
case "B" -> new ServiceB();
default -> throw new IllegalArgumentException("Unknown type");
};
}
}
Factory Pattern creates objects dynamically, based on parameters!
class VehicleFactory {
public static Vehicle getVehicle(String type) {
return switch (type) {
case "Car" -> new Car();
case "Bike" -> new Bike();
default -> throw new IllegalArgumentException("Unknown type");
};
}
}
Factory hides object creation logic from the client!
Question 188: Does Abstract Factory Pattern use Factory Pattern inside?
Yes! The Abstract Factory itself contains multiple Factory Methods that return related objects.
Abstract Factory is a higher-level design pattern that uses the Factory Pattern internally.
<h1>@ViewData["Title"]</h1>
2⃣ Using ViewBag (Dynamic Property)
ViewBag.User = "John Doe";
<h1>Welcome, @ViewBag.User</h1>
3⃣ Using Model (Strongly Typed Data)
public class UserModel { public string Name { get; set; } }
return View(new UserModel { Name = "John" });
<h1>Welcome, @Model.Name</h1>
Question 38: In the Same Request, Can ViewData Persist Across Actions?
No, ViewData does NOT persist across actions.
✔ It only exists for the duration of the current request.
✔ For persistent data across actions, use TempData.
Question 75: What HTTP Status Code is Used for Unauthorized Access?
Two Common Status Codes:
Status Code When is it Used?
401 Unauthorized User not authenticated (No token, expired token)
403 Forbidden User authenticated but lacks permission
Question 80: How is the Token Passed in JavaScript, jQuery, Angular, etc.?
Common ways to send tokens in JS frameworks:
Framework Method
JavaScript (Fetch Authorization: Bearer <token> in headers
API)
jQuery AJAX beforeSend: function(xhr) { xhr.setRequestHeader("Authorization", "Bearer
<token>"); }
Angular (HttpClient) { headers: new HttpHeaders({ 'Authorization': 'Bearer ' + token }) }
React (Axios) axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
// Retrieve Token
const token = await EncryptedStorage.getItem("auth_token");
Question 85: Whose Expiry Time is More: Access Token or Refresh Token?
Refresh Tokens last longer than Access Tokens because they are used only to request a new access token.
Example:
• Access Token: 15 min
• Refresh Token: 7 days
Question 86: How to Revoke a Refresh Token?
If a user logs out or a security breach occurs, revoke the refresh token:
1⃣ Invalidate the refresh token in the database (if stored server-side).
2⃣ Blacklist the token (store invalid tokens to prevent reuse).
3⃣ Rotate Refresh Tokens (generate a new one each time and store only the latest one).
Question 89: How to Secure JWT in Cookies from XSS & CSRF Attacks?
Use HttpOnly, Secure, and SameSite attributes.
✔ HttpOnly → Prevents JavaScript access
✔ Secure → Only works over HTTPS
✔ SameSite → Blocks unauthorized cross-site requests
Key Takeaways
• C# 6.0+ (2016, .NET Core 1.0) → Introduced cleaner syntax ($"", ?., =>).
• C# 7.x (2017-2018, .NET Core 2.0/2.1) → Focused on performance optimizations (Tuples, Pattern
Matching, Span<T>).
• C# 8.0 (2019, .NET Core 3.0) → Introduced modern programming features (Nullable Reference
Types, Async Streams).
• C# 9.0 (2020, .NET 5) → Made code more immutable and cleaner (Records, Init-Only Setters).
• C# 10.0 (2021, .NET 6 LTS) → Improved developer productivity (Global Usings, File-Scoped
Namespaces).
• C# 11.0 (2022, .NET 7) → Focused on strong typing and performance (Required Members, Generic
Math).
Difference Between FCL (Framework Class Library) and BCL (Base Class Library)
base Keyword in C#
The base keyword in C# is used to refer to the base (parent) class from a derived (child) class. It allows
accessing:
1⃣ Base Class Methods & Properties
2⃣ Base Class Constructors
3⃣ Base Class Fields
Summary
Feature Usage
Call Base Method base.MethodName();
Call Base Constructor : base(parameters)
Access Base Field base.FieldName;
Use in Method Overriding base.MethodName(); inside overridden method
Difference Between Literal and Variable in C#
Memory Layout in C#
Variable Type Memory Location Lifetime Example
Local Variables (Value Stack Exists only during int x = 10;
Types) function execution
Reference Type Stack (reference) + Heap Exists until Garbage string name = "John";
Variables (actual object) Collection (GC)
Instance Variables Heap (inside object) Exists as long as the class Person { int age; }
(Class Fields - Non- object exists
Static)
Static Variables Static Memory (part of Exists for the static int counter = 0;
Heap, separate from object program's lifetime
instances)
Constants (const) Stored in Code Section Exists for program const double PI = 3.14;
(Read-Only Memory) lifetime
Readonly Fields Heap (if instance) / Static Set only in readonly int id;
(readonly) Memory (if static) constructor
Global Variables Static Memory Exists for program static class Config {
(inside a static class) lifetime public static string
AppName; }
readonly Keyword in C#
The readonly keyword in C# is used to define fields whose values can only be assigned at the time of
declaration or within a constructor. Once assigned, they cannot be modified elsewhere in the program.
Key Features of readonly
Value can only be set in the constructor or at declaration.
Prevents accidental modifications after initialization.
Useful for defining immutable fields in a class.
Works with instance (readonly int x;) and static (static readonly int y;) fields.
this Keyword in C#
The this keyword in C# is a reference to the current instance of a class. It is primarily used to access members
(fields, properties, methods) of the same object inside a class.
Indexers in C#
Indexers in C# allow objects to be accessed like an array using square brackets []. They let you define custom
logic for accessing data in a class, similar to properties but with indexed values.
Indexers vs Properties
Feature Properties Indexers
Access Type Access a single value Access multiple values using an index
Syntax object.Property object[index]
Parameters None Can take one or more parameters
Use Case Get/set a single value Get/set multiple values dynamically
var result = from num in numbers where num > 30 select num;
var result = numbers.Where(num => num > 30);
What is Serialization?
Serialization is the process of converting an object into a format (like JSON, XML, or binary) that can be
stored in a file, database, or sent over a network.
Why use Serialization?
• Save object state to a file or database.
• Transfer objects over a network (API, web services).
• Store settings in a structured format.
2⃣ What is Deserialization?
Deserialization is the process of converting serialized data back into a C# object.
Why use Deserialization?
• Read and restore saved object states.
• Convert received JSON/XML into objects.
• Process API responses efficiently.
3⃣ Types of Serialization in C#
1. Binary Serialization → Stores data in binary format (faster, but not human-readable).
2. XML Serialization → Converts objects to XML format.
3. JSON Serialization → Converts objects to JSON format (commonly used in APIs).
4. Custom Serialization → Custom logic using ISerializable interface.
5. Reflection Methods in C#
6. Reflection in C# allows you to inspect assemblies, types, methods, properties, fields, and attributes
at runtime. It is part of the System.Reflection namespace.
7.
8. 1⃣ Important Reflection Methods
Method Description
GetType() Gets the runtime type of an object.
Assembly.GetExecutingAssembly() Gets the currently executing assembly.
Assembly.Load("assemblyName") Loads an assembly dynamically.
Type.GetMethods() Retrieves all public methods of a type.
Type.GetProperties() Gets all public properties of a type.
Type.GetFields() Gets all fields (public/private).
Type.GetConstructors() Gets all constructors of a type.
Type.GetInterfaces() Lists the interfaces implemented by a type.
MethodInfo.Invoke(obj, parameters[]) Calls a method dynamically at runtime.
yield Keyword in C#
The yield keyword in C# is used in iterators to return elements one at a time without storing the entire
collection in memory. It improves performance and memory efficiency when working with large data
sequences.
Summary
Feature LINQ (Sequential) PLINQ (Parallel LINQ)
Execution Mode Single-threaded Multi-threaded
Performance Slower for large datasets Faster for CPU-bound operations
Order Preserved Not guaranteed (unless .AsOrdered() is used)
Use Case Small datasets, I/O operations Large datasets, CPU-heavy tasks
Task in C# (.NET)
• A Task in C# represents an asynchronous operation that runs in the background without blocking the
main thread. It is a fundamental part of Task Parallel Library (TPL) and is used for concurrent
programming.
•
• Why Use Tasks?
• ✔ Improves application responsiveness by running operations in the background.
✔ Utilizes multicore processors efficiently.
✔ Allows for better exception handling compared to threads.
✔ Supports cancellation and continuation.
✔ Works seamlessly with async and await keywords.
Summary Table
Return Type Description
IActionResult General return type for multiple responses (Ok(), BadRequest(), etc.).
ActionResult<T> Strongly typed version of IActionResult.
JsonResult Returns JSON data.
ContentResult Returns raw text, HTML, or XML.
ViewResult Returns an HTML view.
PartialViewResult Returns a partial HTML view.
RedirectResult Redirects to an external URL.
RedirectToActionResult Redirects to an action within the app.
FileResult Returns a file for download.
NotFoundResult Returns a 404 Not Found response.
Summary Table
Action Method HTTP Verb Description
Index() GET Default method returning a view.
Details(int id) GET Fetches data using parameters.
[HttpGet] GetData() GET Explicitly handles GET requests.
[HttpPost] SubmitForm() POST Handles form submissions.
[HttpPut] UpdateData() PUT Updates existing records.
[HttpDelete] DeleteData() DELETE Deletes a resource.
[HttpPatch] PatchData() PATCH Partially updates a resource.
[HttpGet("api/custom-route/{id}")] GET Defines a custom API route.
[NonAction] HelperMethod() N/A Marks method as non-action.
async Task<IActionResult> GetDataAsync() GET Handles async operations.