0% found this document useful (0 votes)
43 views73 pages

Dot Net Interview Questions

.NET is a framework for building applications, while C# is a programming language used to develop on the .NET platform. The document also covers the differences between .NET Framework, .NET Core, and .NET 5.0, as well as concepts like Intermediate Language (IL), Just-In-Time (JIT) compilation, and the importance of the Common Language Runtime (CLR) and Garbage Collector (GC). Additionally, it discusses managed vs unmanaged code, value types vs reference types, and the advantages of using generic collections.

Uploaded by

adef17354
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views73 pages

Dot Net Interview Questions

.NET is a framework for building applications, while C# is a programming language used to develop on the .NET platform. The document also covers the differences between .NET Framework, .NET Core, and .NET 5.0, as well as concepts like Intermediate Language (IL), Just-In-Time (JIT) compilation, and the importance of the Common Language Runtime (CLR) and Garbage Collector (GC). Additionally, it discusses managed vs unmanaged code, value types vs reference types, and the advantages of using generic collections.

Uploaded by

adef17354
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 73

Question 1: Difference Between .

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.

Question 2: .NET Framework vs .NET Core vs .NET 5.0


Feature .NET Framework .NET Core .NET 5.0 and Later
Release Year 2002 2016 2020 (for .NET 5)
Platform Windows-only Cross-platform (Windows, Cross-platform
Linux, macOS)
Performance Slower compared to Core Faster, lightweight Even more
optimized
Application Legacy Windows applications Modern web, cloud, Unified for all
Type (WinForms, WPF, ASP.NET microservices, and console application types
MVC) apps
Open Source Partially open-source Fully open-source Fully open-source
Future Support No new updates (only security Actively developed (until Long-term future
patches) .NET 5) direction of .NET
Package Uses GAC (Global Assembly Uses NuGet packages Uses NuGet
Management Cache) packages
Deployment Heavy, requires full installation Lightweight, supports self- Same as .NET Core
contained deployment
Key Points
• .NET Framework is Windows-only, best for legacy applications.
• .NET Core is cross-platform and ideal for modern applications.
• .NET 5 and later (like .NET 6, .NET 7, .NET 8) unify .NET Core and Framework into one platform.
Question 3: What is IL (Intermediate Language) Code?
Intermediate Language (IL), also known as MSIL (Microsoft Intermediate Language) or CIL (Common
Intermediate Language), is the low-level, machine-independent code generated by the C# compiler (csc.exe)
before execution.
When a C# program is compiled, it is not directly converted into machine code. Instead, it is converted into IL
code, which is later compiled into machine code by the JIT (Just-In-Time) compiler at runtime.

Question 4: What is the use of JIT (Just-In-Time Compiler)?


The Just-In-Time (JIT) Compiler converts Intermediate Language (IL) code into native machine code just
before execution. This process happens at runtime, ensuring efficient execution of the program.
How JIT Works?
1. C# code → Compiled into IL code → Stored in DLL or EXE.
2. When the application runs, the CLR (Common Language Runtime) loads the IL code.
3. JIT compiles the IL into native machine code specific to the operating system (Windows, Linux,
macOS).
4. The CPU executes the native code.
Types of JIT Compilers
• Normal JIT – Compiles methods when they are first called and stores them in memory.
• Econo JIT – Compiles methods when called but does not store them.
• Pre-JIT (AOT - Ahead of Time Compilation) – Compiles all IL code at once (used in NGen - Native
Image Generator).

Question 5: Is it possible to view IL code?


Yes, you can view IL code using tools like:
1. ILDasm (Intermediate Language Disassembler)
o Installed with Visual Studio.
o Open Developer Command Prompt and run:
ildasm yourfile.exe
2. dotPeek (JetBrains) – A popular .NET decompiler.
3. dnSpy – A powerful open-source IL viewer and debugger.
4. ILSpy – A lightweight IL code browser.

Question 6: What is the benefit of compiling into IL code?


Key Benefits of IL Code Compilation
1. Platform Independence – IL code is not tied to any specific CPU architecture. This allows .NET
applications to run on different platforms (Windows, Linux, macOS) using .NET Core/.NET 5+.
2. Security & Code Verification – The CLR performs checks on IL code before execution to ensure
safety, preventing memory corruption and illegal operations.
3. Optimized Performance – The JIT compiler optimizes IL code at runtime, generating machine code
specific to the processor, leading to faster execution.
4. Language Interoperability – Different languages (C#, VB.NET, F#) compile into IL, allowing
seamless interaction between them.
5. Efficient Memory Management – The Garbage Collector (GC) in .NET works efficiently with IL
code for memory optimization.
Conclusion
IL code provides a balance between performance, security, and portability, making .NET a powerful
framework for modern software development.
Question 8: What is CLR (Common Language Runtime)?
The Common Language Runtime (CLR) is the execution environment of .NET applications. It is
responsible for managing code execution, memory, security, and exception handling.
Key Features of CLR:
1. Just-In-Time (JIT) Compilation – Converts IL into machine code.
2. Garbage Collection – Automatically manages memory.
3. Security Management – Provides code access security (CAS).
4. Exception Handling – Handles runtime errors.
5. Thread Management – Supports multi-threading.
6. Type Safety – Ensures strong type checking.
How CLR Works?
1. C# Code → Compiled into IL (by the C# compiler)
2. IL Code → Executed by CLR using JIT compilation
3. Native Code → Runs on CPU
Analogy
Think of the CLR as a virtual machine that manages and optimizes the execution of .NET applications, just
like the JVM (Java Virtual Machine) does for Java.
Question 9: What is Managed and Unmanaged Code?
Feature Managed Code Unmanaged Code
Definition Code executed by the CLR. Code executed directly by the OS.
Memory Managed automatically by Garbage Developer manually manages memory (e.g.,
Management Collector (GC). using malloc() and free()).
Security & Type CLR ensures security, type safety, and No built-in security or type safety.
Safety exception handling.
Examples C#, VB.NET, F# (all .NET languages). C, C++, Assembly, COM components.
Performance Slightly slower due to JIT and GC Faster but prone to memory leaks and
overhead. crashes.

Question 10: Explain the importance of Garbage Collector (GC)?


The Garbage Collector (GC) in .NET automatically reclaims unused memory, preventing memory leaks and
improving application performance.
Key Benefits of Garbage Collector
1. Automatic Memory Management – Developers don’t need to manually free memory.
2. Prevents Memory Leaks – Removes unused objects, avoiding memory waste.
3. Avoids Dangling Pointers – Eliminates the risk of accessing invalid memory locations.
4. Optimized Performance – Uses Generational Garbage Collection for efficiency.
5. Thread-Safe – Runs in the background without interfering with application execution.
How GC Works in .NET?
1. Marks – Identifies unused objects.
2. Sweeps – Removes unreferenced objects.
3. Compacts – Reorganizes memory for efficient allocation.
Generations in Garbage Collection
• Gen 0 – Short-lived objects (e.g., local variables).
• Gen 1 – Objects promoted from Gen 0.
• Gen 2 – Long-lived objects (e.g., static variables, cached data).
GC is triggered when:
• System runs low on memory.
• GC.Collect() is manually called (not recommended).
• A threshold of allocated memory is reached.

Question 11: Can Garbage Collector claim unmanaged objects?


No, the Garbage Collector (GC) cannot directly manage unmanaged objects like:
• File handles
• Database connections
• Network sockets
• COM objects
• Unmanaged memory allocated via malloc()
How to Handle Unmanaged Resources in .NET?
1. Use Dispose() method (via IDisposable interface).
2. Use finalize (destructor) method for cleanup.
3. Use SafeHandle for OS-level resource management.
Summary
• GC does NOT handle unmanaged resources.
• Always implement IDisposable or SafeHandle to clean up unmanaged resources.
• Use using statements to ensure resources are released properly.

Question 12: What is the importance of CTS (Common Type System)?


The Common Type System (CTS) defines the rules for data types in .NET, ensuring that all languages using
the .NET framework can interact with each other smoothly.

Key Benefits of CTS:

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.

CTS Data Type Categories:

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

Question 13: Explain CLS (Common Language Specification)?

The Common Language Specification (CLS) is a subset of CTS that defines a set of rules all .NET
languages must follow to ensure interoperability.

Key CLS Rules:

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.

• Allows cross-language compatibility in .NET.


• Ensures reusability of code written in different .NET languages.

Question 14: Difference Between Stack vs. Heap?


Feature Stack Heap
Storage Type Stores value types (int, float, struct). Stores reference types (class, object,
array, delegate).
Memory Allocation Fast and managed automatically (LIFO). Dynamic allocation (slower than stack).
Lifetime Local to a method and cleared when Exists until garbage collection reclaims it.
method exits.
Access Speed Faster (direct access). Slower (indirect access via pointers).
Memory Automatically cleaned up. Garbage Collector (GC) reclaims memory.
Management

Question 15: What are Value Types & Reference Types?


Feature Value Type Reference Type
Storage Stored in the stack. Stored in the heap (reference in stack).
Data Copy Copies value when assigned to a new Copies reference (address) when
variable. assigned.
Example int, float, char, bool, struct, enum. class, object, string, array, delegate.
Types

Question 16: Explain Boxing and Unboxing?

Boxing and Unboxing allow value types to be treated as reference types.

Boxing (Value Type → Object)

• Converts value type into object/reference type (stored in the heap).


• Example:
int num = 10;
object obj = num; // Boxing (num stored in heap)

Unboxing (Object → Value Type)

• Extracts value type from an object.


• Example:
object obj = 10;
int num = (int)obj; // Unboxing (obj converted back to stack memory)

Question 17: What is the consequence of Boxing and Unboxing?

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

Better Approach: Use Generics (Avoids Boxing/Unboxing):


List<int> numbers = new List<int>(); // No boxing needed

Question 18: Explain Casting, Implicit Casting, and Explicit Casting?

Casting in .NET

byte → short → int → long → float → double

char → int

Casting is converting one data type into another.

Implicit Casting (Safe & Automatic)

• Happens when converting smaller to larger data types.


• No data loss, done automatically.
• Example:
int num = 100;
double d = num; // Implicit casting (int → double)

Explicit Casting (Manual)

• Happens when converting larger to smaller data types.


• Requires explicit conversion, may cause data loss.
• Example:
double d = 9.78;
int num = (int)d; // Explicit casting (double → int) (Data loss: 9.78 → 9)

Question 19: What Can Happen During Explicit Casting?

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)

3. Invalid Cast Exception – Casting incompatible types causes runtime errors.


object obj = "Hello";
int num = (int)obj; // Runtime error: InvalidCastException

Best Practices for Safe Casting

• Use as Operator (returns null if conversion fails).


object obj = "Hello";
string str = obj as string; // Safe casting (no exception)

• Use is Operator (checks before casting).


if (obj is int number)
Console.WriteLine(number);

Conclusion

• Implicit Casting = Safe, automatic (no data loss).


• Explicit Casting = Manual, may cause data loss, overflow, or exceptions.
• Use as and is for safer reference type conversions.

Question 20: Difference Between Array and ArrayList


Feature Array ArrayList
Type Fixed-size collection of elements of the Dynamic collection that can store different data
same type. types.
Namespace System System.Collections
Size Fixed at declaration. Cannot grow or Dynamic. Can resize automatically when
shrink. elements are added.
Performance Faster (type-safe and no Slower (boxing/unboxing occurs when storing
boxing/unboxing). value types).
Type Safety Strongly typed (only stores one type). Weakly typed (stores object, requiring type
casting).
Example int[] arr = new int[5]; ArrayList list = new ArrayList();

Question 21: Which Has Better Performance: Array or ArrayList?


• Arrays perform better than ArrayLists because they:
o Are strongly typed (no need for boxing/unboxing).
o Use contiguous memory allocation.
o Have less overhead compared to dynamic collections.
Result: Arrays perform faster due to their static nature.

Question 22: What Are Generic Collections?


Generic collections are type-safe, reusable collections introduced in .NET 2.0 under
System.Collections.Generic. They eliminate boxing/unboxing and improve performance.
Examples of Generic Collections
Collection Description Example
List<T> Dynamic list (similar to ArrayList, List<int> nums = new List<int>();
but type-safe).
Dictionary<TKey, Key-value pair collection. Dictionary<int, string> dict = new
TValue> Dictionary<int, string>();
Queue<T> FIFO (First-In, First-Out). Queue<string> q = new Queue<string>();
Stack<T> LIFO (Last-In, First-Out). Stack<int> stack = new Stack<int>();
Example of Generic Collection (List<T> vs ArrayList):
csharp
CopyEdit
// Using List<T> (Generic Collection)
List<int> numbers = new List<int> { 1, 2, 3 };
numbers.Add(4); // No boxing/unboxing needed

// Using ArrayList (Non-Generic)


ArrayList list = new ArrayList();
list.Add(10); // Boxing occurs (int → object)
Why Use Generic Collections?
• Better performance (no boxing/unboxing).
• Type safety (compile-time error prevention).
• More features (e.g., List<T>.Find(), Dictionary<TKey,TValue>).

Question 23: What Are Threads (Multithreading)?


A thread is the smallest unit of execution within a process.
• Multithreading allows multiple tasks (threads) to run simultaneously.
• Increases CPU utilization by handling multiple tasks in parallel.
Example of a Thread in C#:
csharp
CopyEdit
using System;
using System.Threading;
class Program
{
static void PrintNumbers()
{
for (int i = 1; i <= 5; i++)
{
Console.WriteLine(i);
Thread.Sleep(1000); // Simulate work (1 sec delay)
}
}

static void Main()


{
Thread t1 = new Thread(PrintNumbers);
t1.Start(); // Start a new thread

Console.WriteLine("Main thread running...");


}
}
Output (Runs in parallel):
arduino
CopyEdit
Main thread running...
1
2
3
4
5

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

Feature Threads (System.Threading) TPL (System.Threading.Tasks)


Type Manual thread creation. Uses Tasks and async/await.
Performance More overhead (manual thread Optimized (Thread Pool is managed
management). automatically).
Scaling Hard to scale. Scales efficiently using CPU cores.
Example Thread t = new Thread(Method); t.Start(); Task.Run(() => Method());
TPL is recommended for better performance.

Question 25: How Do We Handle Exceptions in C# (try/catch)?


Exception Handling Blocks
1. try – Code that may throw an exception.
2. catch – Handles exceptions if they occur.
3. finally – Runs always (whether an exception occurs or not).

Question 26: What Is the Need for finally?


The finally block is always executed, even if an exception is not thrown.
• Used for clean-up tasks (closing files, releasing memory, etc.).
When to Use finally?
• Closing file/database connections
• Releasing unmanaged resources
• Freeing up memory

Summary of Key Concepts


Array vs. ArrayList – Arrays are faster & type-safe, while ArrayLists are dynamic but slower.
Generic Collections – Improve performance by removing boxing/unboxing.
Threads vs. TPL – TPL (Task) is better optimized than manual threads.
Exception Handling (try/catch/finally) – Prevents crashes and ensures cleanup.

Question 27: Why Do We Need the out Keyword?

The out keyword in C# is used to pass arguments by reference, allowing a method to return multiple values.

Key Features of out:


The parameter must be assigned a value inside the method.
It allows a method to return more than one value.
It is similar to ref, but ref requires an initial value.

Use Case: Returning multiple values from a method without using a class or struct.

Question 28: What Is the Need for Delegates?

A delegate is a type-safe function pointer that allows methods to be passed as parameters.

Why Use Delegates?


Enables callback functions (executing a method dynamically).
Supports event-driven programming.
Allows flexibility in defining method execution at runtime.
Use Case: Delegates are useful in event handling, callbacks, and LINQ.

Question 29: What Are Events?

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

Events are encapsulayion over delegates

Why Use Events?


Loosely coupled communication between classes.
Follows the Observer Pattern (subscribers get notified).
Commonly used in GUI applications, notifications, and real-time updates.

Use Case: Events are used in GUI applications, logging systems, and event-driven architectures.

Summary of Key Concepts

out → Passes variables by reference & allows multiple return values.


Delegates → Function pointers enabling callbacks & flexibility.
Events → Used for notifications & real-time updates in applications.

Difference Between Abstract Class and Interface in C#


Both abstract classes and interfaces are used to define contracts in C#, but they have key differences in their
behavior and use cases.

Key Differences: Abstract Class vs Interface


Feature Abstract Class Interface
Definition Can have both abstract and concrete Can only have method declarations (before
(implemented) methods C# 8.0)
Method Can contain implemented methods Cannot contain implementations (before C#
Implementation 8.0)
Fields/Variables Can have fields (variables) Cannot have fields, only constants
Constructors Can have constructors Cannot have constructors
Multiple Cannot support multiple inheritance Supports multiple inheritance (a class can
Inheritance (can only inherit one class) implement multiple interfaces)
Access Modifiers Supports public, protected, private All methods are public by default
members
Use Case Used when you need shared Used when you only need method
functionality + abstraction contracts
Use Case: Use abstract classes when some methods need implementation while others must be
overridden.

Use Case: Use interfaces when you only need method contracts without implementation.

4⃣ When to Use Abstract Class vs Interface?


Scenario Use Abstract Class Use Interface
You need to provide default behavior Yes No
You need to enforce a contract for multiple unrelated classes No Yes
You need fields/variables Yes No
You need multiple inheritance No Yes
Question 31: What is a Delegate and How to Create One?
A delegate in C# is a type-safe function pointer that allows methods to be passed as parameters. It acts like a
reference to a method and can be used to call that method dynamically.

How to Create a Delegate?


1⃣ Declare a delegate (matching the method signature).
2⃣ Create a method with the same signature.
3⃣ Instantiate the delegate and call the method.
Example: Creating & Using a Delegate

class Program
{
// Step 1: Declare a delegate
delegate void MyDelegate(string message);

// Step 2: Create a method matching the delegate signature


static void ShowMessage(string msg)
{
Console.WriteLine(msg);
}

static void Main()


{
// Step 3: Instantiate and invoke the delegate
MyDelegate del = new MyDelegate(ShowMessage);
del("Hello, Delegates!");
}
}
Use Case: Delegates are used for callbacks, event handling, and flexible method execution.
Different Delegate Types
Delegate Type Description Use Case
Single-Cast Calls one method Callback execution
Multi-Cast Calls multiple methods Event handling
Func<> Returns a value LINQ, calculations
Action<> Returns void Logging, UI updates
Predicate<> Returns boolean Filtering, validation
Anonymous Method without name Inline methods, events
Lambda Short-form anonymous method LINQ, functional programming
Async Runs asynchronously Multi-threading

Question 32: Where Have You Used Delegates?


Delegates are commonly used in:
✔ Event handling (GUI, Button Clicks)
✔ Callbacks (e.g., processing data asynchronously)
✔ LINQ & Functional Programming
✔ Threading (Background execution)
✔ Plug-and-play architectures (selecting different implementations at runtime)

Question 33: What is a Multicast Delegate?


A multicast delegate is a delegate that holds references to multiple methods. When the delegate is invoked, it
calls all methods in the invocation list.
Use Case: Used in event handling when multiple methods should be executed.

Question 34: What is an Event?


An event in C# is a specialized delegate that allows a class to notify other classes when something happens.
Key Features of Events:
✔ Based on Delegates (but more restrictive)
✔ Subscribers cannot directly invoke an event
✔ Ensures encapsulation and controlled method execution
Example Use Case: Button Click Event, Notifications, Logging.

Question 35: How to Create an Event?


Example: Creating and Using an Event

class EventExample
{
public delegate void NotifyHandler(string message);
public event NotifyHandler OnNotify; // Event declaration

public void TriggerEvent()


{
if (OnNotify != null)
OnNotify("Event Triggered!"); // Invoke event
}
}

class Program
{
static void ShowNotification(string msg)
{
Console.WriteLine(msg);
}

static void Main()


{
EventExample obj = new EventExample();

// Subscribe to the event


obj.OnNotify += ShowNotification;

obj.TriggerEvent(); // Trigger the event


}
}
Output:
Event Triggered!
Use Case: Used in UI programming, event-driven architectures, and notification systems.

Question 36: Difference Between Delegate and Event


Feature Delegate Event
Definition Function pointer for calling methods Encapsulated delegate used for notifications
dynamically
Invocation Can be called directly Cannot be invoked directly (only by the
declaring class)
Encapsulation Public, can be accessed and modified Restricted to only be triggered within the
outside the class class
Multicast Supports multiple method references Supports multiple subscribers
Support
Use Case Call methods dynamically (callbacks, Notify subscribers when an action occurs
functional programming) (event-driven programming)
Key Takeaway:
✔ Use delegates for callbacks and method references.
✔ Use events for notifying subscribers when something happens.

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.

Question 37: Why Do We Need OOP?


Object-Oriented Programming (OOP) is needed to create scalable, maintainable, and reusable software. It
helps in organizing complex systems by using objects and principles like encapsulation, inheritance, and
polymorphism.
Benefits of OOP:
✔ Code Reusability (via Inheritance)
✔ Data Hiding (via Encapsulation)
✔ Flexibility & Maintainability
✔ Modular Code Structure
✔ Real-World Representation (e.g., Objects like "Car" and "Animal")

Question 38: What Are the Important Pillars of OOP?


The 4 Pillars of OOP are:
1⃣ Encapsulation → Hiding data (private fields, getters/setters)
2⃣ Abstraction → Hiding complex implementation details
3⃣ Inheritance → Reusing existing functionality
4⃣ Polymorphism → Multiple forms (method overloading & overriding)

Question 39: What Is a Class and Object?


Class → A blueprint for objects. It defines properties (fields) and behaviors (methods).
Object → A real instance of a class.

Question 40: Abstraction vs Encapsulation?


Feature Abstraction Encapsulation
Definition Hides complex implementation Hides data (fields)
Purpose Reduce complexity Protect data
How? Using abstract classes & interfaces Using private fields & public methods
Example abstract classes, interface private variables, getters/setters

Question 41: Explain Inheritance?


Inheritance allows one class (child) to acquire properties & methods of another class (parent).
Use Case: Reduces duplicate code and improves maintainability.

Question 42: Explain virtual Keyword?


The virtual keyword is used to allow method overriding in derived classes.
Use Case: Enables polymorphism by allowing derived classes to modify base class behavior.

Question 43: What Is Overriding?


Method Overriding allows a child class to modify a method already defined in the parent class.
Rules:
✔ Use virtual in the base class.
✔ Use override in the derived class.
Use Case: Used when a child class needs a modified behavior.

Question 44: Explain Overloading?


Method Overloading allows multiple methods with the same name but different parameters.
Use Case: Improves code readability by using one method name for multiple operations.

Question 45: Overloading vs Overriding?


Feature Overloading Overriding
Definition Same method name, different Same method name & parameters, but
parameters different behavior
How? Same class Parent-child relationship
Keyword Used? No special keyword virtual (base), override (child)
Compile-Time / Compile-time polymorphism Runtime polymorphism
Runtime?
Example Add(int a, int b) vs Add(int a, int b, Show() in parent overridden by Show() in
int c) child
Key Takeaway:
✔ Use Overloading when methods perform similar tasks but with different inputs.
✔ Use Overriding when a child class needs to modify parent class behavior.
Summary
OOP makes code reusable, maintainable, and scalable.
Encapsulation & Abstraction → Data Hiding.
Inheritance → Code Reusability.
Polymorphism (Overloading & Overriding) → Multiple Forms.

Question 46: Explain Static vs Dynamic Polymorphism?


Polymorphism means "one name, many forms" and is categorized into Static (Compile-time) and Dynamic
(Runtime) Polymorphism.
Feature Static Polymorphism (Compile-time) Dynamic Polymorphism (Runtime)
Definition Method resolution occurs at compile-time. Method resolution occurs at runtime.
How it works? Method Overloading & Operator Method Overriding.
Overloading.
Performance Faster (Resolved at compile-time). Slower (Resolved at runtime).
Keywords No special keyword. virtual (in base), override (in derived).
Used?
Example Add(int a, int b) vs Add(int a, int b, int c). Show() in parent overridden by Show() in
child.
Key Takeaway:
✔ Use Static Polymorphism for compile-time method differentiation (Overloading).
✔ Use Dynamic Polymorphism for runtime behavior modification (Overriding).

Question 47: Explain Operator Overloading?


Operator Overloading allows us to define how operators (+, -, *, etc.) work for user-defined types (e.g.,
custom classes).
Operators That CAN Be Overloaded
Category Operators
Unary Operators +, -, !, ~, ++, --, true, false
Binary Arithmetic Operators +, -, *, /, %
Bitwise Operators &, `
Comparison Operators ==, !=, >, <, >=, <=
Assignment Operators (Cannot be overloaded directly, but +=, -= work via + and - overloads)
Conversion Operators implicit, explicit (for custom type conversions)

Operators That CANNOT Be Overloaded


Operator Reason
= (Assignment) Cannot change object assignment behavior
&&, `
. (Member Access) Cannot be changed
:: (Scope Resolution) Cannot be changed
?: (Ternary) Cannot be changed
sizeof Already defined for data types
typeof Determines metadata, not applicable for overloading
new Used for object creation
is, as Used for type checking/casting

Key Takeaway:
✔ Allows custom behavior for operators.
✔ Improves readability (c1 + c2 is better than Add(c1, c2)).
✔ Cannot overload =, &&, ||, new, typeof, etc.

Question 48: Why Do We Need Abstract Classes?


An abstract class serves as a base class that provides a blueprint for derived classes.
Why Use Abstract Classes?
✔ Enforces structure (child classes must implement abstract methods).
✔ Code Reusability (common functionality shared across child classes).
✔ Cannot be instantiated (ensures logical hierarchy).
Key Takeaway:
✔ Use abstract classes when you want to force child classes to implement specific methods.
✔ Helps in maintaining common functionalities while allowing custom behaviors in derived classes.

Question 49: Are Abstract Methods Virtual?


Yes, abstract methods are implicitly virtual because they must be overridden in derived classes.
Abstract method example:
Key Difference Between abstract and virtual:
✔ virtual → Can be overridden but has a default implementation.
✔ abstract → Must be overridden in derived classes (no default implementation).

Question 50: Can We Create an Instance of an Abstract Class?


No, you cannot create an instance of an abstract class.
Key Takeaway:
✔ Abstract classes act as blueprints and must be inherited.
✔ Only derived (non-abstract) classes can be instantiated.
Key Differences Between abstract and virtual
Feature abstract virtual
Can have No (Must be overridden) Yes (Can be overridden)
implementation?
Forces child class to Yes No (Optional)
override?
Can be instantiated? No (Abstract classes can't be Yes (Regular classes can be
instantiated) instantiated)
Use case? Enforce method implementation in Provide default behavior but allow
derived classes modification

When to Use Which?


Scenario Use abstract? Use virtual?
Enforcing child classes to implement a method Yes No
Providing a default method implementation No Yes
Making the method optional for child classes to override No Yes
Framework design (base class that shouldn't be instantiated) Yes No
Question 51: Is it compulsory to implement abstract methods?
Yes, when a class inherits an abstract class, it must implement all abstract methods unless it is itself abstract.
Example
abstract class Animal
{
public abstract void MakeSound(); // Abstract method
}

class Dog : Animal


{
public override void MakeSound() // Must override the method
{
Console.WriteLine("Bark!");
}
}
✔ If Dog does not override MakeSound(), it will cause a compilation error.
Exception: If Dog was also declared abstract, then it wouldn’t need to implement MakeSound().

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.

Question 53: Explain interfaces and why do we need them?


An interface defines a contract (set of methods/properties) that a class must implement.
Why do we need interfaces?
✔ To achieve multiple inheritance.
✔ To enforce a standard structure for different classes.
✔ To allow loose coupling and dependency injection.

Question 54: Can we write logic in an interface?


Yes, from C# 8+, interfaces can contain default method implementations using the default keyword.

Before C# 8, interfaces couldn’t have method implementations.

Question 55: Can we define methods as private in an interface?


Yes, but only in C# 8+ and only for default implementations.
✔ private methods help break large default methods into smaller ones.
Without C# 8, interfaces could only have public methods.

Question 56: If I want to change an interface, what’s the best practice?


Best Practices for Changing Interfaces
✔ Create a new interface instead of modifying an existing one.
✔ Use interface extension to prevent breaking existing code.
✔ Use explicit interface implementation if needed.
✔ New classes can use the extended interface.
Question 59: Explain Multiple Inheritance in Interface?
C# does NOT support multiple inheritance with classes, but interfaces allow it.
✔ A class can inherit multiple interfaces.
Why use multiple interfaces?
✔ Keeps code modular and reusable.
✔ Prevents issues from multiple class inheritance.

Question 60: Explain the Interface Segregation Principle (ISP)?


ISP is one of the SOLID principles that says:
✔ Don’t force a class to implement unnecessary methods.
✔ Split large interfaces into smaller, more specific ones.
Why is this better?
✔ Dog only implements IAnimal, so it’s not forced to implement Swim().
✔ Fish implements both IAnimal & ISwimmer, making the code flexible.

Question 61: Can we create an instance of an interface?


No, you cannot create an instance of an interface because interfaces do not have implementations.
Key Takeaway: You can’t instantiate an interface, but you can use a reference of an interface pointing to
an implementing class.

Question 63: Abstract Class vs Interface (Interview Questions & Answers)


Feature Abstract Class Interface
Inheritance Single Multiple
Method Can have methods with code Cannot have implementation (except C# 8+
Implementation default methods)
Constructors Can have constructors Cannot have constructors
Access Modifiers Can be public, protected, etc. Methods are always public (except C# 8+ private
methods)
Fields & Properties Can have fields Cannot have fields
Best Used For When you want default When you want only a contract
functionality
Key Takeaway:
✔ Use an interface for defining only behaviors.
✔ Use an abstract class when you need default implementations.

Question 64: Why do we need constructors?


✔ A constructor is a special method that initializes an object when it is created.
Key Takeaway: Without constructors, we would have to manually set initial values for objects.

Question 65: In a Parent-Child relationship, which constructor fires first?


✔ The parent constructor executes first, followed by the child constructor.
Key Takeaway: The base (parent) class constructor runs first before the child class constructor.

Question 66: How are initializers executed?


✔ Instance initializers execute before the constructor in the order they appear.
Example
class Example
{
int x = Initialize(); // Runs before constructor

public Example()
{
Console.WriteLine("Constructor executed");
}

int Initialize()
{
Console.WriteLine("Initializer executed");
return 10;
}
}

Example obj = new Example();


// Output:
// Initializer executed
// Constructor executed
Key Takeaway: Instance initializers execute before constructors.

Question 67: How are static constructors executed in Parent-Child?


✔ Static constructors execute only once per class and run before any instance is created.
✔ Parent's static constructor executes first, then the child’s static constructor.
Key Takeaway: Static constructors run only once per class, and parent's static constructor runs first.

Question 68: When does a static constructor fire?


✔ A static constructor fires automatically when:
1⃣ The class is referenced for the first time.
2⃣ Any static method or field is accessed.
Key Takeaway: A static constructor runs only once per class, before any object creation.

Question 69: What is Shadowing?


✔ Shadowing (new keyword) occurs when a derived class redefines a member of the base class without
overriding it.
Example
class Parent
{
public string Name = "Parent";
}

class Child : Parent


{
public new string Name = "Child"; // Shadowing Parent's field
}

Child obj = new Child();


Console.WriteLine(obj.Name); // Output: Child
Key Takeaway: new hides the parent’s member instead of overriding it.

Question 70: Explain Method Hiding?


✔ Method Hiding occurs when a derived class redefines a base class method using the new keyword.
Example
class Parent
{
public void Show() { Console.WriteLine("Parent Method"); }
}

class Child : Parent


{
public new void Show() { Console.WriteLine("Child Method"); }
}

Child obj = new Child();


obj.Show(); // Output: Child Method
✔ If new is not used, a compiler warning will occur.
✔ Method hiding does NOT support polymorphism like override.
Key Takeaway:
✔ Use override for polymorphism.
✔ Use new for method hiding (not recommended in most cases).

Question 71: Shadowing vs Overriding


Feature Shadowing (new keyword) Overriding (override keyword)
Definition Hides a base class method without Replaces a base class method in derived
replacing it class
Keyword Used new override
Polymorphism No Yes
Support
Parent Method Call Still accessible via base.MethodName() Can be accessed using
base.MethodName()
Compile-Time Yes, if new is not explicitly used No warning
Warning
Key Takeaway:
✔ Use override for polymorphism.
✔ Use new only when you want to explicitly hide a method without replacing it.

Question 72: When do we need Shadowing?


✔ Shadowing (new keyword) is used when you want to redefine a method in a derived class without
modifying the base class's behavior.
When to use Shadowing?
1⃣ When the base class method cannot be changed but needs a different behavior in the derived class.
2⃣ When you don't want polymorphic behavior and need separate implementations for base and derived
classes.
3⃣ When upgrading legacy code to introduce new behavior without modifying the base class.
Key Takeaway: Use shadowing only if you don’t need polymorphism. Otherwise, use overriding.
Question 73: Explain Sealed Classes
✔ A sealed class is a class that cannot be inherited.
Example
Key Takeaway:
✔ Use sealed when you want to prevent inheritance and ensure the class cannot be modified further.

Question 74: Can we create an instance of a sealed class?


✔ Yes, a sealed class can be instantiated like a normal class, but it cannot be inherited.
Key Takeaway: Sealed classes can be instantiated, but they cannot be extended.

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.

Question 76: Can a Nested Class access Outer Class variables?


✔ Yes, but only if the variable is static or the inner class has an instance of the outer class.
Example: Accessing a static member
class Outer
{
private static string message = "Hello from Outer";

public class Inner


{
public void Show() { Console.WriteLine(message); } // Allowed
}
}

Outer.Inner obj = new Outer.Inner();


obj.Show(); // Output: Hello from Outer
Key Takeaway:
✔ Nested classes can access outer class members if they are static or if an instance is passed.

Question 77: Can we have public/protected access modifiers in nested classes?


✔ Yes, a nested class can be public, private, protected, or internal, but it depends on the outer class’s
accessibility.
Example
class Outer
{
public class PublicNested { } // Allowed
private class PrivateNested { } // Allowed
protected class ProtectedNested { } // Allowed
}
Key Takeaway: Nested classes can have all access modifiers, but their accessibility depends on the outer
class.

Question 78: Explain Partial Classes


✔ A partial class allows a single class to be split across multiple files.
✔ Both files combine into one class at runtime!
Key Takeaway: Use partial classes to manage large codebases efficiently.

Question 79: When do we use Partial Classes?


✔ Partial classes are useful when:
1⃣ Splitting large classes across multiple files.
2⃣ Working in teams, allowing multiple developers to work on different parts of the class.
3⃣ Using auto-generated code (e.g., Windows Forms, ASP.NET).
Key Takeaway: Partial classes improve code organization in large projects.

Question 80: What is SOLID?


✔ SOLID is a set of five design principles for writing maintainable and scalable code.
Principle Description
S: Single Responsibility Principle A class should have one responsibility only.
(SRP)
O: Open/Closed Principle (OCP) A class should be open for extension but closed for
modification.
L: Liskov Substitution Principle (LSP) A child class should be substitutable for its parent class.
I: Interface Segregation Principle (ISP) Clients should not be forced to depend on unused interfaces.
D: Dependency Inversion Principle High-level modules should not depend on low-level modules.
(DIP)

81: What is the full form of SOLID?


✔ SOLID stands for:

S: Single Responsibility Principle (SRP)


O: Open/Closed Principle (OCP)
L: Liskov Substitution Principle (LSP)
I: Interface Segregation Principle (ISP)
D: Dependency Inversion Principle (DIP)

Question 82: What is the goal of SOLID?


✔ The goal of SOLID principles is to create:
1⃣ Maintainable and scalable software.
2⃣ Flexible code that adapts to changes.
3⃣ Loose coupling and high cohesion in design.
4⃣ Fewer bugs by enforcing good coding practices.
5⃣ Reusable components across different projects.

Question 83: Explain SRP (Single Responsibility Principle) with an Example?


✔ Definition: A class should have only one reason to change, meaning it should have only one responsibility.
Question 84: What is the benefit of SRP?
✔ Benefits of SRP:
1⃣ Improves maintainability – Changes in one part don’t affect the other.
2⃣ Increases code readability – Easier to understand.
3⃣ Encourages reusability – Components can be reused elsewhere.
4⃣ Reduces bugs – Fewer dependencies mean fewer errors.

Key Takeaway: Always separate responsibilities to avoid tightly coupled code.

Question 85: Explain OCP (Open/Closed Principle) with an Example?


✔ Definition:

A class should be open for extension but closed for modification.


We should extend behavior without modifying existing code.
Bad Example (OCP Violation) – Modifying a class for every new feature:
✔ Now, adding a new payment method doesn’t require modifying existing code.

Question 86: What is the benefit of OCP?


✔ Benefits of OCP:
1⃣ Prevents code modification when adding new features.
2⃣ Supports scalability – Easily extend functionality.
3⃣ Encourages modularity – Code is well-structured and reusable.

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 89: Explain Interface Segregation Principle (ISP)?


✔ Definition:

A class should not be forced to implement interfaces it does not use.


Large interfaces should be split into smaller, specific interfaces.
Bad Example (ISP Violation) – Forcing classes to implement unnecessary methods:

Key Takeaway: Split large interfaces into smaller, focused ones.

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:

LSP prevents subclasses from breaking parent behavior.


ISP ensures that classes only implement what they need, avoiding unnecessary dependencies.
✔ If LSP is violated, it might indicate ISP should be applied.

Question 91: Define Dependency Inversion Principle (DIP)?


✔ Definition:

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.

Question 92: What is Higher-Level Module and Lower-Level Module?


✔ Higher-Level Module:

Contains business logic and core functionality.


Should not depend on lower-level details.
Example: DataService, PaymentProcessor, OrderManager.
✔ Lower-Level Module:

Provides specific implementations (e.g., database, API calls).


Example: MySQLDatabase, SQLServerDatabase, StripePayment.
Key Takeaway:

Higher-level modules should depend on abstractions, NOT lower-level implementations.

Question 93: How Does Dependency Inversion Benefit? (Example)


✔ Benefits of DIP:
1⃣ Loose Coupling – Reduces dependencies between components.
2⃣ Easier to Maintain – Changes in implementation won’t break the system.
3⃣ More Flexible & Extensible – Easily switch components (e.g., databases, loggers).

Question 94: Will Only Dependency Inversion Solve Decoupling?


✔ No! Dependency Inversion alone does not fully solve decoupling.

✔ Other techniques are needed:

Dependency Injection (DI) – Inject dependencies instead of creating them.


Inversion of Control (IoC) – Let a framework manage dependencies.
Factory Pattern – Creates objects dynamically.
Key Takeaway: DIP reduces coupling, but IoC & DI provide full flexibility.

Question 95: Why Move Object Creation Outside High-Level Modules?


✔ Reasons:
1⃣ Avoid tight coupling – High-level modules should not instantiate dependencies.
2⃣ Easier unit testing – Can mock dependencies for testing.
3⃣ Flexible configurations – Easily change implementations without modifying business logic.
Question 96: Explain IoC (Inversion of Control)?
✔ Definition:

IoC moves control of object creation & dependency management to a framework.


Instead of creating objects manually, let a framework provide them.
✔ IoC container manages dependencies and injects them when needed.

Question 97: Explain Dependency Injection (DI) With an Example?


✔ Definition:

DI is a technique to inject dependencies instead of creating them.


It supports Dependency Inversion by allowing objects to receive dependencies from outside.
Example – Constructor Injection

csharp
Copy
Edit
class DataService
{
private readonly IDatabase _database;

public DataService(IDatabase database) { _database = database; }

public void GetData() { _database.Connect(); }


}
✔ Now, DataService does not create an IDatabase instance.
✔ It receives the dependency via constructor injection.

Question 98: Are SOLID, IoC, and DI Design Patterns or Principles?


✔ Category Breakdown:

Concept Type
SOLID Design Principles
IoC Architectural Pattern
DI Design Pattern

Key Takeaway:

SOLID improves code design.


IoC shifts control of dependencies.
DI injects dependencies dynamically.
Question 99: Is SOLID Enough for Good Architecture?
✔ No! SOLID is just one part of good architecture.

✔ Other important principles:


1⃣ DRY (Don’t Repeat Yourself) – Avoid duplication.
2⃣ KISS (Keep It Simple, Stupid) – Keep code readable & simple.
3⃣ YAGNI (You Ain’t Gonna Need It) – Don’t add features unless necessary.
4⃣ CQRS (Command Query Responsibility Segregation) – Separate read/write logic.

Key Takeaway: SOLID is important, but not the only principle for good software architecture.

Question 100: What Are Different Types of "Using/Has A" Relationships?


✔ Types of Relationships in OOP:

Relationship Definition Example


Association ("Has-A") One class uses another Car has a Engine
Aggregation (Weak Association) One class can exist without the other Company has employees
Composition (Strong Association) One class cannot exist without the other House has rooms (Rooms
cannot exist without House)
Inheritance ("Is-A") One class inherits another Dog is a Animal
Dependency ("Uses") One class depends on another temporarily Logger uses FileWriter
Key Takeaway:

Composition is preferred over Inheritance for code flexibility.


Use Dependency Injection instead of tight coupling in Has-A relationships.

Question 101: What is a Composition Relationship?


✔ Definition:
• Composition is a strong "Has-A" relationship where one object owns another, and the contained
object cannot exist independently.
• If the parent object is destroyed, the child object is also destroyed.
Example – Composition in C#
class Engine
{
public void Start() { Console.WriteLine("Engine started."); }
}

class Car
{
private readonly Engine _engine; // Strong dependency

public Car() { _engine = new Engine(); } // Engine created inside Car

public void StartCar() { _engine.Start(); }


}
✔ Car owns Engine, and if the Car object is deleted, the Engine object is also deleted.

Question 102: Explain Aggregation?


✔ Definition:
• Aggregation is a weaker "Has-A" relationship, where the contained object can exist independently.
• If the parent object is destroyed, the child object can still exist.
Example – Aggregation in C#
class Employee
{
public string Name { get; set; }
}
class Company
{
private readonly List<Employee> _employees;

public Company(List<Employee> employees) { _employees = employees; }


}
✔ Employees exist independently and are passed into the Company class.

Question 103: Explain Association?


✔ Definition:
• Association is the most general "uses-a" relationship where two classes are linked but do not depend
on each other.
Example – Association in C#
class Driver
{
public void Drive(Car car) { Console.WriteLine("Driving the car."); }
}
✔ Driver and Car are associated but can exist independently.

Question 104: Composition vs Aggregation vs Association


Feature Composition Aggregation Association
Dependency Strong Medium Weak
Strength
Object One object owns the other One object uses another, but No strict ownership
Ownership both can exist separately
Object Lifetime If the parent dies, the child If the parent dies, the child still No impact on object
dies exists lifecycle
Example Car has-a Engine (Engine Company has-a Employee Driver uses Car (Both
exists only inside Car) (Employee exists independently) can exist separately)

Question 105: UML Symbols for Composition, Aggregation, and Association


✔ UML Notation:
Relationship Symbol
Composition Filled Diamond ( )
Aggregation Hollow Diamond (◇)
Association Straight Line (—)

Question 106: Explain Stack and Heap?


✔ Stack:
• Stores value types and method execution order (LIFO).
• Faster access but limited memory.
✔ Heap:
• Stores reference types (objects, arrays, classes).
• Larger memory space, but slower access.

Question 107: Where are Stack and Heap Stored?


✔ Both Stack and Heap are part of RAM:
• Stack is managed directly by the CPU.
• Heap is managed by Garbage Collector (GC).

Question 108: What Goes on Stack and What Goes on Heap?


✔ Stack:
• Value types (int, double, bool, char, struct).
• Local variables inside a method.
• Method call execution order.
✔ Heap:
• Reference types (class, object, string, array, delegate).
• Objects created using new keyword.

Question 109: How is the Stack Memory Address Arranged?


✔ Stack memory is arranged in LIFO (Last In, First Out) order.
• Each new method call pushes a stack frame.
• When a method ends, the frame is popped off the stack.

Question 110: How is Stack Memory Deallocated (LIFO or FIFO)?


✔ LIFO (Last-In, First-Out)
• The last function pushed is the first to be removed.

Question 111: How are Primitive and Objects Stored in Memory?


✔ Primitive (Value Type) → Stored in Stack.
✔ Objects (Reference Type) → Reference stored in Stack, Object stored in Heap.

Question 112: Can Primitive Data Types Be Stored in Heap?


✔ Yes, but only inside objects or boxing/unboxing.
Example – Boxing (Value Type → Heap)

Question 113: Explain Value Types and Reference Types?


Type Stored In Example
Value Type Stack int, float, char, bool, struct
Reference Type Heap class, interface, object, string

Question 114: Explain ByVal and ByRef?


✔ ByVal (Pass by Value)
• Creates a copy of the variable.
• Changes inside the method do not affect the original variable.
✔ ByRef (Pass by Reference)
• Passes memory address, so changes affect the original variable.
Example – ByVal vs ByRef
void ChangeValue(int x) { x = 20; } // ByVal
void ChangeReference(ref int x) { x = 20; } // ByRef

int num = 10;


ChangeValue(num); // num is still 10
ChangeReference(ref num); // num is now 20
ref Keyword in C#
The ref keyword in C# is used to pass arguments by reference rather than by value. This means that changes
made to the parameter inside the method affect the original variable in the calling method.

When to Use ref?


• When you want a method to modify the value of a variable.
• When passing large structures to avoid performance overhead.
• When a method needs to return multiple values via parameters.

How ref Works


1. The variable must be initialized before passing it to the method.
2. Changes in the method affect the original variable.
Example: Using ref to Modify a Value
csharp
CopyEdit
using System;

class Program
{
static void UpdateValue(ref int number)
{
number += 10; // Changes the original value
}

static void Main()


{
int x = 5;
UpdateValue(ref x);
Console.WriteLine(x); // Output: 15
}
}
Without ref, the value of x would remain 5 because parameters are passed by value by default.

ref with Reference Types


Even with reference types (like objects), using ref allows replacing the reference itself.
Without ref, myObj would still point to the old object.

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

When NOT to Use ref


• When modifying values is not necessary.
• When working with small data types, as passing by value is faster.
• When working with multi-threaded code (because it can lead to unexpected side effects).
Question 115: Copy By Value vs Copy By Reference?
Copy Type What Happens? Example
Copy by Value New copy is created int a = 5; int b = a;
Copy by Reference Points to same memory Person p1 = new Person(); Person p2 = p1;
Question 116: What is Boxing and Unboxing?
✔ Boxing: Converting a value type (stack) into a reference type (heap).
✔ Unboxing: Converting a reference type (heap) back into a value type (stack).
✔ Boxing moves data from stack to heap (slow).
✔ Unboxing moves data from heap to stack (slow).

Question 117: Is Boxing/Unboxing Good or Bad?


✔ Bad for performance, because:
• Consumes extra memory (object stored in heap).
• Slows execution (heap allocation & garbage collection overhead).
• Unnecessary CPU cycles due to casting.
✔ Good when unavoidable, but should be minimized.

Question 118: Can We Avoid Boxing and Unboxing?


✔ Yes, by using generics instead of object type.
✔ Generics prevent unnecessary heap allocations and improve performance.

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 120: Are Strings Allocated on Stack or Heap?


✔ Strings are allocated on the Heap, but are immutable (cannot be changed after creation).
✔ String literals are stored in a special memory area called the String Intern Pool.
✔ String literals are pooled to optimize memory.

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 122: How Are Stack and Heap Memory Deallocated?


✔ Stack: Automatically deallocated when method exits (LIFO order).
✔ Heap: Managed by Garbage Collector (GC).
Example – Stack Deallocation
void Method()
{
int x = 10; // Allocated in stack
} // x is automatically removed from stack when Method() exits
✔ Heap objects persist until GC cleans them up.

Question 123: Who Clears the Heap Memory?


✔ Garbage Collector (GC) automatically frees heap memory when objects are no longer referenced.
✔ GC reclaims memory when no references exist.

Question 124: Where Is Structure Allocated – Stack or Heap?


✔ Structs are value types → stored in Stack (when local).
✔ If inside a class, they are stored in Heap.
✔ Standalone structs are on the Stack, struct inside class → Heap.

Question 125: Are Structures Copied by Value or Reference?


✔ Structs are copied by value (just like int, double, etc.).
✔ Each struct copy has independent values.

Question 126: Can Structures Get Created on Heap?


✔ Yes, if the struct is inside a class.
Example
csharp
CopyEdit
class MyClass
{
public MyStruct MyStructInstance; // Struct inside class → stored in Heap
}
✔ Struct inside a class is allocated in Heap.

Question 127: Explain Garbage Collector (GC)?


✔ GC automatically reclaims memory from unreferenced objects in Heap.
✔ Stops the program to clean memory when needed (GC Pause).
GC Phases: 1⃣ Mark → Finds unused objects.
2⃣ Sweep → Removes unreferenced objects.
3⃣ Compact → Defragments heap memory.
Example – GC in Action
✔ Objects without references are cleaned.

Question 128: How Does GC Know When to Clean Objects?


✔ GC runs automatically when:
• Heap is full.
• Application is idle.
• Explicitly called using GC.Collect() (not recommended).

Question 129: Is There a Way to See Heap Memory?


✔ Yes, using:
• Visual Studio Diagnostic Tools
• CLR Profiler
• dotMemory (JetBrains)
Example – Viewing Heap in Visual Studio
1. Open Diagnostic Tools in Visual Studio (Ctrl + Alt + F2).
2. Check Heap Snapshot.

Question 130: Does Garbage Collector Clean Primitive Types?


✔ No, GC does not clean primitive types (int, float, bool).
✔ They are stored on the stack and automatically removed when method exits.
Example
void Method()
{
int x = 10; // Stored in stack, automatically removed after Method() exits
}
✔ Only heap objects need GC cleanup.

Question 131: Managed vs Unmanaged Code/Objects/Resources?


✔ Managed Code
• Code executed by CLR (Common Language Runtime).
• Memory managed by Garbage Collector (GC).
• Examples: C#, .NET applications.
✔ Unmanaged Code
• Code executed outside CLR (directly by OS).
• Manual memory management (malloc/free in C++).
• Examples: C++, COM objects, File handles, Database connections.
✔ Unmanaged objects must be freed manually!

Question 132: Can Garbage Collector Clean Unmanaged Code?


✔ No! GC only manages .NET objects in heap.
✔ GC does not clean:
• File handles
• Database connections
• OS resources (e.g., sockets, registry handles, COM objects)
✔ Use Dispose() or finalize for cleanup.
✔ Always free unmanaged resources manually using Dispose().

Question 133: Explain Generations in Garbage Collection?


✔ Generations in GC improve performance by optimizing object cleanup.
✔ GC divides objects into 3 Generations: 1⃣ Gen 0: Newly created, short-lived objects (e.g., method
variables).
2⃣ Gen 1: Objects that survived one GC cycle.
3⃣ Gen 2: Long-lived objects (e.g., static variables, caches).
Example – Object Moving Across Generations
csharp
CopyEdit
MyClass obj = new MyClass(); // Gen 0
GC.Collect(); // Moves surviving objects to Gen 1
GC.Collect(); // Moves further surviving objects to Gen 2
✔ Short-lived objects die quickly (Gen 0), reducing GC overhead!

Question 134: What is GC0, GC1, and GC2?


✔ GC0 (Generation 0) → Most frequent cleanup (fast).
✔ GC1 (Generation 1) → Less frequent cleanup (medium).
✔ GC2 (Generation 2) → Rare cleanup (slow but necessary).

Question 135: Why Do We Need Generations?


✔ Optimizes performance by:
• Cleaning short-lived objects quickly (Gen 0).
• Delaying cleanup for long-lived objects (Gen 2).
• Reducing unnecessary GC cycles for stable objects.
✔ Without generations, GC would scan the entire heap frequently, slowing down the application!

Question 136: Best Place to Clean Unmanaged Objects?


✔ Best practice: Use Dispose() inside using or implement IDisposable.
✔ Always use Dispose() or using to release unmanaged resources!

Question 137: How Does GC Behave When We Have a Destructor?


✔ Destructor (~ClassName()) delays garbage collection!
✔ GC calls destructors during finalization (slow process).
Example
csharp
CopyEdit
class MyClass
{
~MyClass() { Console.WriteLine("Destructor called"); }
}
✔ Avoid destructors unless necessary (use Dispose instead).

Question 138: What Do You Think About an Empty Destructor?


✔ Bad practice
✔ Causes unnecessary GC overhead (objects with destructors move to the finalization queue).

Question 139: Explain Dispose Pattern?


✔ Used for cleaning unmanaged resources manually.
✔ Implements IDisposable.Dispose() method.
✔ Dispose() ensures proper cleanup.

Question 140: Finalize vs Destructor?


Feature Finalize Destructor (~ClassName)
Purpose Cleanup before GC Cleanup before GC
Execution Runs by GC Calls Finalize()
Performance Slow Slow
Control No manual call No manual call
Alternative Dispose() is better Dispose() is better
✔ Destructors should be avoided in favor of Dispose().

Question 142: Can You Force Garbage Collector?


✔ Yes, using GC.Collect(), but not recommended .
✔ Forcing GC is bad for performance.

Question 143: Is It a Good Practice to Force GC?


✔ No!
• GC is optimized, forcing it slows down execution.
• Let CLR decide when to run GC.

Question 144: How Can We Detect Memory Issues?


✔ Tools:
• Visual Studio Memory Profiler
• dotMemory (JetBrains)
• CLR Profiler

Question 145: How to Find the Exact Source of Memory Issues?


✔ Use memory profiling tools to analyze object retention and heap allocation.

Question 146: What is a Memory Leak?


✔ Objects that are no longer used but still referenced, preventing GC cleanup.
✔ Solution: Avoid static collections holding objects indefinitely.

Question 147: Can .NET Apps Have Memory Leaks Despite GC?
✔ Yes! If objects are referenced indefinitely.

Question 148: How to Detect Memory Leaks in .NET?


✔ Use memory profilers to track object retention.

Question 149: Explain Weak vs Strong References?


✔ Strong Reference: Prevents GC from collecting an object.
✔ Weak Reference: Allows GC to collect the object if needed.
✔ Weak references help avoid memory leaks.

Question 150: When Will You Use Weak References?


✔ For caching frequently used objects that should not prevent GC cleanup.

Question 151: What Are Design Patterns?


✔ Reusable solutions to common software design problems.
✔ Help improve code structure, maintainability, and scalability.

Question 152: Different Types of Design Patterns?


Different Types of Design Patterns
Design patterns are common solutions to recurring software design problems. They provide best practices and
standard approaches for designing software systems. Design patterns are categorized into three main types:

1⃣ Creational Design Patterns


These patterns focus on object creation mechanisms, aiming to increase flexibility and reuse of code. They help
control object instantiation and improve system performance.
Examples:
• Singleton → Ensures a class has only one instance and provides a global access point.
• Factory Method → Creates objects without specifying the exact class type.
• Abstract Factory → Provides an interface for creating families of related objects.
• Builder → Separates the construction of complex objects from their representation.
• Prototype → Creates new objects by copying an existing object instead of instantiating new ones.

2⃣ Structural Design Patterns


These patterns deal with the organization and composition of classes and objects to form larger structures
efficiently.
Examples:
• Adapter → Allows incompatible interfaces to work together by acting as a bridge.
• Composite → Treats individual objects and compositions of objects uniformly (e.g., tree structures).
• Decorator → Adds additional behavior to objects dynamically without modifying them.
• Facade → Provides a simplified interface to a larger body of code.
• Proxy → Controls access to an object, adding security, caching, or lazy initialization.
• Bridge → Decouples an abstraction from its implementation so they can vary independently.
• Flyweight → Reduces memory usage by sharing common objects instead of creating new ones.

3⃣ Behavioral Design Patterns


These patterns focus on communication and interaction between objects, ensuring loose coupling and better
system organization.
Examples:
• Observer → Defines a dependency between objects so that when one object changes, all its dependents
are notified automatically (e.g., event listeners).
• Strategy → Defines a family of algorithms and lets the client choose one at runtime.
• Command → Encapsulates a request as an object, allowing parameterization and queuing of requests.
• State → Allows an object to change its behavior when its internal state changes.
• Template Method → Defines a skeleton of an algorithm and allows subclasses to fill in the details.
• Mediator → Centralizes communication between objects, reducing dependencies.
• Memento → Captures and restores an object's internal state without violating encapsulation.
• Visitor → Adds new operations to objects without modifying their structure.
• Chain of Responsibility → Passes a request along a chain of handlers until one handles it.

Why Use Design Patterns?


Improve code reusability and maintainability
Promote best practices and industry standards
Reduce coupling between components
Enhance system scalability and flexibility
Make code more readable and understandable

Question 153: Explain Structural, Behavioral, and Creational Design Patterns?


✔ Creational → Object creation (Factory, Singleton).
✔ Structural → Class composition & relationships (Adapter, Proxy).
✔ Behavioral → Object communication (Observer, Strategy).

Question 154: Explain Singleton Pattern and Its Use?


✔ Ensures only one instance of a class exists.
✔ Used for logging, database connections, configuration settings.
Question 155: How Did You Implement Singleton Pattern?
✔ Using private constructor and static instance property.
Thread-safe Singleton:
csharp
CopyEdit
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton() { }
public static Singleton Instance => instance;
}

Question 156: Can We Use Static Class Instead of Private Constructor?


✔ Yes, but static classes cannot implement interfaces or inheritance.
✔ Singleton allows lazy initialization, static does not.

Question 157: Static vs Singleton Pattern?


Feature Static Class Singleton
Instance No instance, all static methods Only one instance
Inheritance No Yes
Lazy Loading No Yes
Thread Safety No Yes
✔ Use Singleton when you need an instance, static for utility classes.

Question 158: How Did You Implement Thread Safety in Singleton?


✔ Using lock mechanism.
Thread-Safe Singleton:
csharp
CopyEdit
public sealed class Singleton
{
private static Singleton instance;
private static readonly object lockObj = new object();

private Singleton() { }

public static Singleton Instance


{
get
{
lock (lockObj)
{
return instance ??= new Singleton();
}
}
}
}

Question 159: What Is Double-Check Locking in Singleton?


✔ Optimized thread safety by checking instance before and inside the lock.
✔ Improves performance by avoiding unnecessary locks.

Question 160: Can Singleton Be Simplified Using Lazy<T>?


✔ Yes! Lazy<T> ensures thread safety and lazy initialization.
✔ No need for locks, works efficiently in multithreading.

Question 161: Can we get rid of this double null-check code?


Yes, in most cases, we can replace the double-checked locking pattern (used in singleton implementations)
with more modern and efficient approaches such as:
• Using volatile in Java or Lazy<T> in C# to ensure thread safety.
• Using a static property (C#) or Bill Pugh Singleton (Java) to avoid explicit locks.
• Relying on dependency injection (DI) instead of manually implementing singletons.
However, if double-checked locking is necessary, ensure it is properly implemented to avoid synchronization
issues.

Question 162: What is the use of the Repository Pattern?


The Repository Pattern is used to abstract the data access logic and separate it from the business logic.
Provides a clean abstraction over database operations.
Centralizes query logic and promotes code reuse.
Enables unit testing by allowing easy mocking of the data layer.
Makes it easier to switch from one ORM (e.g., EF, Hibernate, Dapper) to another.

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 164: What is the Generic Repository Pattern?


A Generic Repository provides a common interface for all entities, reducing repetitive code.
Example in C#:
Promotes code reuse
Reduces duplication for basic CRUD operations
Works with multiple entity types
However, a Generic Repository can be too generic and may need specialization for complex queries.

Question 165: Is abstraction the only benefit of the Repository Pattern?


No! While abstraction is a key benefit, the Repository Pattern also provides:
Encapsulation of data access logic
Decoupling between the business logic and database layer
Unit testing support with mockable repositories
Consistent API for data operations
Better maintainability by centralizing query logic

Question 166: How to implement transactions in a Repository?


A Unit of Work (UoW) pattern is typically used to handle transactions within a repository.
Ensures atomic operations
Prevents partial updates
Supports rollback on failure

Question 167: What is the Unit of Work (UoW) Design Pattern?


The Unit of Work Pattern ensures that multiple repository operations are treated as a single transaction.
Manages multiple repositories within a transaction
Ensures data consistency
Improves performance by reducing unnecessary database calls
Example:
Instead of calling .SaveChanges() for each repository operation, Unit of Work commits changes once all
operations succeed.

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 169: Did you do unit testing with the Repository?


Yes! The Repository Pattern makes unit testing easier by allowing mocking of data access.
Example (Mocking a Repository 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" });
No real database needed
Faster test execution
Easier to write independent unit tests

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

var service = new ProductService(mockRepo.Object); // Inject mock repo


var product = await service.GetProductById(1);

Assert.Equal("Laptop", product.Name); // Assert expected behavior


No real DB calls
Faster execution
Ensures test isolation
Would you like an example in Java or Python?

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 174: What is IoC and DI?


Inversion of Control (IoC) and Dependency Injection (DI) are related but not the same:
IoC (Inversion of Control) → A principle where the flow of control is inverted (i.e., the framework
manages object creation instead of the application).
DI (Dependency Injection) → A technique for achieving IoC by injecting dependencies rather than
instantiating them manually.
IoC = The principle (control is inverted)
DI = The implementation (dependencies are injected)

Question 175: DI vs IoC?


Feature Inversion of Control (IoC) Dependency Injection (DI)
Definition A design principle that inverts control A technique to implement IoC
Focus Who controls the flow of execution How dependencies are injected
Implementation Multiple ways (Factory, Service Locator, DI) Only through injecting dependencies
Example Spring Framework (IoC container) @Autowired (Spring DI)
DI is a way to achieve IoC, but IoC can be implemented in other ways (like Service Locator).

Question 176: What is a Service Locator?


The Service Locator Pattern provides a central registry to fetch dependencies instead of injecting them
directly.
Example in Java:
java
CopyEdit
class ServiceLocator {
private static Map<Class<?>, Object> services = new HashMap<>();

public static <T> void register(Class<T> clazz, T instance) {


services.put(clazz, instance);
}

public static <T> T getService(Class<T> clazz) {


return clazz.cast(services.get(clazz));
}
}
Centralized service access
Can introduce hidden dependencies

Question 177: Service Locator vs DI?


Feature Service Locator Dependency Injection
Control Object asks for dependencies Dependencies are provided automatically
Coupling Higher (Service registry needed) Lower (Loose coupling)
Testability Harder (hidden dependencies) Easier (explicit dependencies)
Flexibility Central registry can be useful More adaptable with DI frameworks
DI is generally preferred over Service Locator because it promotes loose coupling and better testability.
Question 178: Which is better to use, Service Locator or DI?
Dependency Injection (DI) is better in most cases because:
Easier to test (mock dependencies)
Loose coupling (dependencies are passed, not requested)
Better maintainability
Service Locator is useful when:
• A centralized registry is required.
• Dependencies are dynamically resolved at runtime.
TL;DR: Use DI unless there's a strong reason to use Service Locator.

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 180: Is DI a Factory Pattern?


Not exactly!
DI and Factory Pattern both handle object creation, but they serve different purposes:
Feature Dependency Injection (DI) Factory Pattern
Purpose Inject dependencies into a class Encapsulate object creation logic
Control Framework-controlled Manually controlled
Usage Used for managing dependencies Used for creating different objects dynamically
Example @Autowired (Spring), @Inject (C#) VehicleFactory.create("Car")
DI is NOT a Factory Pattern, but DI frameworks internally use factories!

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!

Question 182: Static DI vs Dynamic DI?


Static DI and Dynamic DI are two ways to inject dependencies:
Aspect Static DI Dynamic DI
Definition Dependencies are assigned manually Dependencies are automatically injected
Example Constructor injection (new Service()) Spring @Autowired, Guice, etc.
Flexibility Less flexible (fixed at compile time) More flexible (resolved at runtime)
Maintenance Harder to modify dependencies Easier to swap dependencies
Usage Simple apps with few dependencies Large-scale applications needing modularity

Question 183: When to use Static DI vs Dynamic DI?


Use Static DI when:
• The dependencies won’t change (e.g., small projects).
• You need better performance (avoids reflection).
• You are not using a DI framework.
Use Dynamic DI when:
• You need flexibility (swap implementations easily).
• You are working on large applications (e.g., Spring Boot, .NET Core).
• You want better testability (mock dependencies easily).

Question 184: What is the real Factory Pattern?


The Factory Pattern provides an interface for object creation, but lets subclasses decide which class to
instantiate.
Example (Java Factory Method Pattern)
java
CopyEdit
abstract class Vehicle {
abstract void drive();
}

class Car extends Vehicle {


void drive() { System.out.println("Driving a car"); }
}

class Bike extends Vehicle {


void drive() { System.out.println("Riding a bike"); }
}

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 185: Factory Method vs Factory Pattern?


The Factory Method Pattern is a specific type of Factory Pattern where object creation is delegated to
subclasses.
Aspect Factory Pattern Factory Method Pattern
Control Factory decides which class to instantiate Subclasses decide which class to instantiate
Inheritance Uses a single factory class Uses an abstract class with factory methods
Example VehicleFactory.getVehicle("Car") Abstract class with createVehicle()

Factory Method is more extensible than Simple Factory.

Question 186: How are new behaviors created in Factory Pattern?


By creating new subclasses that extend the factory.
By adding new concrete classes implementing a common interface.
By modifying the Factory Method to support new object types.
Key Idea: The factory should be open for extension, but closed for modification (Open-Closed
Principle).

Question 187: What is the Abstract Factory Pattern?


The Abstract Factory Pattern is a factory of factories that groups related objects together.
Creates families of related objects
Prevents mixing incompatible object types
Useful for frameworks requiring multiple variations of objects

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.

Question 189: What is the Simple Factory Pattern?


The Simple Factory Pattern is the most basic form of the Factory Pattern.
Centralizes object creation
Hides instantiation logic from the client
Uses a single static method to create objects

Question 190: Simple Factory vs Factory (Factory Method) vs Abstract Factory?


Feature Simple Factory Factory Method Abstract Factory
Control Centralized creation in one Delegates creation to Creates related families of
class subclasses objects
Flexibility Hardcoded logic (less flexible) Can be extended Highly flexible
Complexit Simple Medium High
y
Example VehicleFactory.getVehicle("Car CarFactory.createVehicle ElectricVehicleFactory.createCar
") () ()
Use Simple Factory for small apps, Factory Method for extensibility, and Abstract Factory for related
object groups.
Question 191: How to remove IF conditions from Simple Factory?
Solution: Use a Map or Reflection!
Using a Map (Java)
No if-else or switch-case!
Easier to add new types without modifying existing code!

Question 1: What is ASP.NET Core MVC?


ASP.NET Core MVC is a lightweight, high-performance, and cross-platform framework for building web
applications using the Model-View-Controller (MVC) architectural pattern.
Key Features:
Cross-platform: Runs on Windows, Linux, and macOS
Lightweight & Modular: Uses middleware-based request pipeline
Built-in Dependency Injection (DI): Manages dependencies automatically
Supports Razor Pages: Simplifies UI development
RESTful API Support: Easily build Web APIs
ASP.NET Core MVC replaces the older ASP.NET MVC with a more flexible and modern framework!

Question 2: ASP.NET WebForms vs MVC vs MVC Core?


Feature ASP.NET WebForms ASP.NET MVC ASP.NET Core MVC
Architecture Event-driven MVC-based MVC-based
View Engine WebForms (.aspx) Razor (.cshtml) Razor (.cshtml)
Performance Slower (ViewState, Postbacks) Faster Fastest (Lightweight)
Control Less control (Server-side) More control More control
Cross-Platform No No Yes
Dependency Injection No Yes Built-in
Middleware Support No No Yes
ASP.NET Core MVC is the future of ASP.NET development!

Question 3: Explain MVC Architecture?


MVC (Model-View-Controller) is a design pattern that separates an application into three main
components:
1⃣ Model: Represents data & business logic (e.g., Entity Framework models).
2⃣ View: Handles UI & presentation (e.g., Razor pages).
3⃣ Controller: Handles user requests and coordinates the Model & View.

Question 4: Why do we have the wwwroot folder?


The wwwroot folder is the default location for static files (CSS, JavaScript, images, etc.) in ASP.NET
Core MVC.
Improves performance by serving files directly
Isolated from backend logic for security
Accessible using / in the URL
Example:
• wwwroot/css/style.css → Accessible at /css/style.css
• wwwroot/images/logo.png → Accessible at /images/logo.png

Question 5: Explain the importance of appsettings.json?


appsettings.json is the configuration file in ASP.NET Core for storing application settings.
Stores database connection strings, API keys, logging settings, etc.
Supports different environments (appsettings.Development.json, appsettings.Production.json).
Replaces web.config from older ASP.NET.

Question 6: How to read configurations from appsettings.json?


Use IConfiguration to read settings.

Question 7: What is Dependency Injection (DI)?


Dependency Injection (DI) is a design pattern where dependencies are injected instead of being
hardcoded.
Removes hardcoded dependencies
Improves testability (Mock objects)
Enhances maintainability & flexibility
Example: Instead of new DatabaseService(), inject it via constructor!

Question 8: Why do we need Dependency Injection?


Reasons to use DI:
Reduces tight coupling between classes
Makes unit testing easier (Mock objects)
Centralizes dependency management
Supports Inversion of Control (IoC)
DI makes code cleaner and more scalable!

Question 9: How do we implement Dependency Injection?


ASP.NET Core provides built-in DI container (IServiceCollection).

Question 10: What is Middleware in ASP.NET Core?


Middleware is a software component that processes requests & responses in the ASP.NET Core
pipeline.
Executed in a pipeline
Can modify requests & responses
Used for authentication, logging, exception handling, etc.
Example of Custom Middleware:
Middleware is a powerful way to handle requests in ASP.NET Core!

Question 11: How to Create Middleware in ASP.NET Core?


Middleware is a class that processes HTTP requests and responses in ASP.NET Core.
Steps to create Middleware:
1⃣ Create a custom middleware class:
public class CustomMiddleware
{
private readonly RequestDelegate _next;

public CustomMiddleware(RequestDelegate next)


{
_next = next;
}
public async Task Invoke(HttpContext context)
{
Console.WriteLine("Middleware before request");
await _next(context);
Console.WriteLine("Middleware after request");
}
}
2⃣ Register middleware in Program.cs:
var app = builder.Build();
app.UseMiddleware<CustomMiddleware>(); // Add custom middleware
app.Run();
Middleware runs in a pipeline, allowing request/response modifications.

Question 12: What does Startup.cs do?


In ASP.NET Core 3.1 and earlier, Startup.cs was used to configure the application.
Responsibilities of Startup.cs:
Configure Services (Dependency Injection, Database, Authentication)
Configure Middleware (Logging, Routing, CORS, Authentication)
Structure of Startup.cs:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers(); // Register services
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)


{
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
}
From .NET 6 onwards, Startup.cs is replaced by Program.cs.

Question 13: ConfigureServices vs Configure Method?


Method Purpose
ConfigureServices(IServiceCollection services) Registers services & dependencies (e.g., DB,
Authentication, DI, Logging).

Configure(IApplicationBuilder app, Defines the HTTP request pipeline (Middleware,


IWebHostEnvironment env) Routing, Authentication, etc.).

Question 14: Different Ways of Doing Dependency Injection (DI)?


Constructor Injection (Most Common)
public class HomeController
{
private readonly IProductService _productService;
public HomeController(IProductService productService)
{
_productService = productService;
}
}
Method Injection
public IActionResult Index([FromServices] IProductService productService)
{
var products = productService.GetProducts();
return View(products);
}
Property Injection
[Inject]
public IProductService ProductService { get; set; }
Constructor Injection is preferred for better testability & maintainability.

Question 15: Scoped vs Transient vs Singleton?


Lifetime Behavior
Transient New instance created every time it is requested
Scoped One instance per request (Same for entire HTTP request)
Singleton One instance for the entire application
Example in Program.cs:
builder.Services.AddTransient<IProductService, ProductService>(); // Transient
builder.Services.AddScoped<IUserService, UserService>(); // Scoped
builder.Services.AddSingleton<ILogger, Logger>(); // Singleton
Use Case:
Transient → Lightweight, stateless services (E.g., EmailService).
Scoped → Services dependent on a request lifecycle (E.g., DbContext).
Singleton → Application-wide shared services (E.g., Configuration, Caching).

Question 16: What is Razor?


Razor is a view engine in ASP.NET Core used to generate dynamic HTML content.
Supports C# inside HTML (@ symbol)
Fast, lightweight, and secure
Provides strong typing & IntelliSense
Example of Razor Code in .cshtml:
<h1>Welcome, @ViewBag.Username!</h1>
@{
var message = "Hello Razor!";
}
<p>@message</p>

Question 17: How to Pass Model Data to a View?


Use a Model to pass data from Controller to View.
1⃣ Create a Model:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
}
2⃣ Pass Data from Controller:
public IActionResult Index()
{
var products = new List<Product>
{
new Product { Id = 1, Name = "Laptop" },
new Product { Id = 2, Name = "Phone" }
};
return View(products);
}
3⃣ Access Data in View (Index.cshtml):
@model List<Product>
<ul>
@foreach (var product in Model)
{
<li>@product.Name</li>
}
</ul>
This is called a Strongly Typed View.

Question 18: What is the use of Strongly Typed Views?


Strongly Typed Views provide type safety and IntelliSense support.
Prevents runtime errors by enforcing compile-time checks
Provides IntelliSense for model properties
Improves code maintainability
Example:
@model Product
<p>@Model.Name</p> <!-- IntelliSense available -->
Using ViewBag or ViewData is weakly typed and error-prone!

Question 19: Explain the Concept of ViewModel in MVC?


A ViewModel is a class that holds only the data required for a specific View.
Prevents over-fetching unnecessary data
Combines multiple models into a single ViewModel
Improves code separation
Example:
public class ProductViewModel
{
public string ProductName { get; set; }
public string Category { get; set; }
}
Controller Passing ViewModel:
public IActionResult Details()
{
var model = new ProductViewModel { ProductName = "Laptop", Category = "Electronics" };
return View(model);
}
View (Details.cshtml):
@model ProductViewModel
<h1>@Model.ProductName - @Model.Category</h1>
ViewModels make Views more efficient and secure!

Question 20: What is Kestrel Web Server?


Kestrel is the built-in, cross-platform web server for ASP.NET Core.
Fast, lightweight, and asynchronous
Supports HTTPS, WebSockets, and Unix sockets
Used as a reverse proxy behind IIS, Nginx, Apache
Runs by default in .NET Core applications:
Kestrel can be configured for better performance and security!

Question 21: Why Kestrel When We Have IIS Server?


Kestrel is the default web server in ASP.NET Core, but IIS is still used as a reverse proxy.
Feature Kestrel IIS
Cross-Platform Yes No (Windows Only)
Performance Very fast Optimized for Windows
Reverse Proxy No Yes (Can act as a proxy for Kestrel)
Security Features Basic Advanced (Logging, Security, SSL, Load Balancing)
Why Use Both?
✔ Kestrel is lightweight & high-performance, but lacks security features.
✔ IIS (or Nginx, Apache) can act as a reverse proxy in front of Kestrel.
Production Setup:
• Use IIS as a reverse proxy with Kestrel (for better security & load balancing).

Question 22: What is the Concept of Reverse Proxy?


A Reverse Proxy is a server that forwards client requests to backend servers.
Why use Reverse Proxy?
✔ Load Balancing → Distributes traffic across multiple backend servers.
✔ Security → Hides backend servers from direct exposure.
✔ Caching → Improves performance by caching responses.
Example with IIS and Kestrel:
1⃣ Client sends a request to IIS
2⃣ IIS forwards request to Kestrel (ASP.NET Core App)
3⃣ Kestrel processes the request & sends a response to IIS
4⃣ IIS sends the final response to the client
Other Reverse Proxies:
• Nginx
• Apache
• HAProxy

Question 23: What Are Cookies?


Cookies are small pieces of data stored in the user's browser by a web server.
Types of Cookies:
✔ Session Cookies → Deleted when the browser closes.
✔ Persistent Cookies → Stored for a specific duration.
Example: Setting a Cookie in ASP.NET Core
Response.Cookies.Append("User", "JohnDoe", new CookieOptions
{
Expires = DateTime.Now.AddDays(7) // Persistent Cookie
});
Retrieving a Cookie:
string userName = Request.Cookies["User"];

Question 24: What is the Need for Session Management?


Since HTTP is a stateless protocol, session management helps maintain user state across requests.
Why do we need sessions?
✔ User Authentication → Keep users logged in.
✔ Shopping Cart → Store items added to the cart.
✔ Personalized User Experience → Store user preferences.

Question 25: Various Ways of Doing Session Management in ASP.NET?


Session Management Method Description
Cookies Stores data in the user's browser.
Session State Stores data on the server.
TempData Short-lived data stored in controllers/views.
Query Strings Passes data via URL parameters.
Hidden Fields Stores data inside form fields.
Database Storage Stores session data in a database for scalability.
Cache Stores temporary session data in memory (like Redis).

Question 26: What Exactly is a Session?


A session is a server-side storage mechanism to maintain user state across multiple HTTP requests.
✔ Stored on the server (not the client)
✔ Uses Session ID (stored in cookies)
✔ Expires after a specific time (default: 20 minutes)

Question 27: Explain "HTTP is a Stateless Protocol"?


Each HTTP request is independent and does not retain any past information.
What does "stateless" mean?
✔ No built-in memory → Every request is new to the server.
✔ Need extra mechanisms (like sessions, cookies) to maintain state.
Example:
1⃣ User logs in → Sends request to server
2⃣ Server authenticates → Responds with data
3⃣ Next request is treated as new (server forgets login state)
Solution:
✔ Use Sessions, Cookies, JWT Tokens, Database storage to maintain user state.

Question 28: Various Ways of Doing Session Management?


1⃣ Session Variables (Server-Side)
HttpContext.Session.SetString("User", "JohnDoe");
var username = HttpContext.Session.GetString("User");
2⃣ Cookies (Client-Side)
Response.Cookies.Append("User", "JohnDoe", new CookieOptions { Expires = DateTime.Now.AddDays(7) });

3⃣ Query Strings (URL-Based)


<a href="/profile?user=JohnDoe">Profile</a>

4⃣ TempData (Short-Lived Data)


TempData["Message"] = "Welcome!";

5⃣ Hidden Fields (Form-Based)


<input type="hidden" name="username" value="JohnDoe" />

6⃣ Database Storage (Scalable Solution)


INSERT INTO UserSession (UserID, SessionData) VALUES (1, 'JohnDoe');
Which One to Use?
✔ Use Session for short-term, server-side storage.
✔ Use Cookies for persistent, client-side storage.
✔ Use Database for scalable, long-term session storage.

Question 29: Are Sessions Enabled by Default?


No, sessions are NOT enabled by default in ASP.NET Core.
You need to explicitly enable sessions in Program.cs.

Question 30: How to Enable Sessions in MVC Core?


Step 1: Add Session Services (Program.cs)
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSession(); // Enable session service
var app = builder.Build();

Step 2: Use Session Middleware (Program.cs)


app.UseSession();
app.Run();

Step 3: Store & Retrieve Session Data in Controller


// Store data in session
HttpContext.Session.SetString("User", "JohnDoe");

// Retrieve data from session


var username = HttpContext.Session.GetString("User");

Step 4: Configure Session Timeout (Optional)


builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(30);
options.Cookie.HttpOnly = true;
});

Question 31: Are Session Variables Shared (Global) Between Users?


No, session variables are NOT shared between users.
Each user gets a unique session identified by a session ID stored in a cookie.
Sessions are user-specific and do not overlap between users.
Example:
• User A sets session: HttpContext.Session.SetString("Role", "Admin");
• User B sets session: HttpContext.Session.SetString("Role", "User");
• They will NOT see each other’s session data!

Question 32: Do Session Variables Use Cookies?


Yes, sessions use cookies to store the session ID.
✔ The actual session data is stored on the server.
✔ The session ID is stored in a cookie (.AspNetCore.Session).
Example:
Cookie Name: .AspNetCore.Session
Value: abc123xyz
The server uses this session ID to retrieve the actual session data.

Question 33: What is a Cookie?


A cookie is a small piece of data stored in the user's browser.
Types of Cookies:
✔ Session Cookie → Expires when the browser closes.
✔ Persistent Cookie → Stored for a defined duration.
Example: Creating a Cookie in ASP.NET Core
Response.Cookies.Append("User", "JohnDoe", new CookieOptions
{
Expires = DateTime.Now.AddDays(7) // Persistent Cookie
});
Reading a Cookie:
string user = Request.Cookies["User"];

Question 34: Explain Idle Timeout in Sessions?


Idle Timeout is the duration after which a session expires if there is no activity.
✔ Default is 20 minutes.
✔ If a user is inactive for the timeout duration, the session is deleted.
✔ Can be configured in Program.cs.
Example: Set Idle Timeout to 30 Minutes
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(30);
options.Cookie.HttpOnly = true;
});

Question 35: What Does a Context Mean in HTTP?


Context in HTTP represents all request-related information during a web request.
In ASP.NET Core, it's represented by HttpContext.
✔ HttpContext.Request → Access request details (headers, cookies, URL).
✔ HttpContext.Response → Modify response data.
✔ HttpContext.Session → Manage session data.
✔ HttpContext.User → Handle authentication.
Example:
var userAgent = HttpContext.Request.Headers["User-Agent"];

Question 36: When Should We Use ViewData?


Use ViewData when passing data from a Controller to a View within the same request.
✔ Stores key-value pairs (like a dictionary).
✔ Data is valid only for the current request.
✔ Useful for small temporary data (e.g., Page Titles, Notifications, etc.)
Example:
ViewData["Message"] = "Welcome to ASP.NET Core!";
<h1>@ViewData["Message"]</h1>

Question 37: How to Pass Data from Controller to View?


Three ways to pass data:
1⃣ Using ViewData (Dictionary, Object Type)
ViewData["Title"] = "Home Page";

<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 39: ViewData vs ViewBag


Feature ViewData ViewBag
Type Dictionary (ViewData["key"]) Dynamic Property (ViewBag.key)
Data Lifetime Current Request Current Request
Strongly Typed? No No
Performance Slightly Faster Slower (uses reflection)
Use Case Best for loops and iterations Best for simple variable passing

Question 40: How Does ViewBag Work Internally?


ViewBag is an alias for ViewData, implemented using dynamic properties.
✔ Internally, ViewBag uses reflection to store data in ViewData.
✔ It is a wrapper around ViewData (which is a dictionary).
✔ Since it uses dynamic properties, it’s slower than ViewData.
ViewBag is implemented like this:
public class ViewBag : DynamicViewData
{
public ViewBag(ViewDataDictionary viewData) { this.ViewData = viewData; }
}
Both ViewData and ViewBag store data in the same dictionary!
ViewData["User"] = "John";
Console.WriteLine(ViewBag.User); // "John"
This means ViewData and ViewBag are interchangeable.

Question 41: Explain ViewModel?


A ViewModel is a class that represents only the data required for a specific view.
✔ It helps in decoupling the UI from the database model.
✔ ViewModel can combine multiple models into one object.
Example: If you have a User model and an Order model but need only UserName and OrderDate in a view,
you create a ViewModel.
public class UserOrderViewModel
{
public string UserName { get; set; }
public DateTime OrderDate { get; set; }
}
Using ViewModel in Controller:
public IActionResult OrderDetails()
{
var viewModel = new UserOrderViewModel
{
UserName = "John Doe",
OrderDate = DateTime.Now
};
return View(viewModel);
}
Using ViewModel in View:
<h1>Order Details</h1>
<p>User: @Model.UserName</p>
<p>Order Date: @Model.OrderDate</p>

Question 42: ViewBag vs ViewModel - What’s the Best Practice?


ViewModel is the best practice for passing data to views.
Feature ViewBag ViewModel
Type Dynamic Strongly Typed Class
Data Structure Key-Value Pairs Well-Defined Class
Performance Slower (Reflection) Faster
Code Readability Harder to Maintain Cleaner Code
Best For Simple Data Complex View Data
Best Practice:
✔ Use ViewModel for structured data.
✔ Use ViewBag only for small, temporary data (e.g., page title).

Question 43: Explain TempData?


TempData is used to store data between HTTP requests (i.e., after a redirect).
✔ Unlike ViewData/ViewBag (which work within the same request), TempData persists across actions.
✔ It is deleted once read.
Example:
TempData["Message"] = "Order Placed Successfully!";
return RedirectToAction("OrderConfirmation");
public IActionResult OrderConfirmation()
{
var message = TempData["Message"]; // Data is now deleted
return View();
}

Question 44: Can TempData Persist Across Action Redirects?


Yes, TempData persists across redirects.
But it is deleted once read unless explicitly preserved.
✔ If not read, it persists automatically.
✔ If read, it is lost unless Keep() or Peek() is used.

Question 45: How Is TempData Different from ViewData?


Feature ViewData TempData
Scope Current Request Persists across Requests
Storage Key-Value (Dictionary) Key-Value (Dictionary)
Persistence Lost after the request Available after Redirect
Use Case Passing data to views Passing data across actions
Example:
✔ ViewData:
ViewData["User"] = "John"; // Exists only in the same request
✔ TempData:
TempData["User"] = "John"; // Exists even after redirect

Question 46: If TempData Is Read, Is It Available for the Next Request?


No, once TempData is read, it is removed from memory.
To persist it, use Keep() or Peek().

Question 47: How to Persist TempData?


Use Keep() or Peek() to keep TempData for multiple requests.

Question 48: What Does Keep() Do in TempData?


Keep() retains TempData after reading, making it available for subsequent requests.
Example:

Question 49: Explain Peek in TempData?


Peek() reads TempData without removing it, keeping it available for the next request.

Question 50: How Is TempData Different from Session Variables?


Feature TempData Session Variables
Storage Location HTTP Context (Short-Lived) Server Memory / Database
Lifetime Until Read (unless Kept) Until Session Expires
Data Persistence Across One or Two Requests Throughout the User's Session
Use Case Temporary Data Long-Term User Data

Question 51: If I Restart the Server, Does TempData or Session Stay?


Session Variables Stay (if session storage is not in-memory).
TempData Does Not Stay (since it uses session but is short-lived).
Session Storage Types:
1. In-Memory (Default) – Lost on restart.
2. Distributed (SQL Server, Redis, etc.) – Persists after restart.
To persist sessions after restart, use a persistent session store (SQL Server, Redis, etc.).

Question 52: Is TempData Private to a User?


Yes, TempData is private to a user.
✔ It is stored in Session Storage, which is user-specific.
✔ Different users have separate TempData values.

Question 53: ViewData vs ViewBag vs TempData vs Session Variables?


Feature ViewData ViewBag TempData Session
Scope Single Request Single Request Across Requests (if not read) Across Requests
Type Dictionary Dynamic Object Dictionary Persistent Storage
Lifetime Lost after Lost after Persists across redirects (if not Persists until
request request read) expired
Data Short-Lived Short-Lived Temporary across requests Long-Term
Retention
Use Case Pass data to Pass data to Redirects Store user session
views views data
Best Practices:
✔ Use ViewModel instead of ViewData/ViewBag for structured data.
✔ Use TempData for redirects.
✔ Use Session for long-term user data.

Question 54: What is WebAPI?


ASP.NET Web API is a framework for building RESTful HTTP services.
✔ It allows applications to expose data and services via HTTP endpoints.
✔ Supports multiple clients (Browsers, Mobile, IoT, etc.).

Question 55: What is the Advantage of WebAPI?


Advantages of Web API:
✔ Lightweight & Fast (Built on HTTP).
✔ Platform Independent (Works on any client: Mobile, Web, IoT).
✔ RESTful Communication (Uses JSON, XML).
✔ Scalable & Secure (Supports authentication, caching, etc.).

Question 56: Explain REST and Architectural Constraints of REST?


REST (Representational State Transfer) is an architectural style for designing networked applications.
✔ REST APIs use standard HTTP methods (GET, POST, PUT, DELETE).
REST Architectural Constraints:
1⃣ Client-Server Architecture → Separation of UI and data storage.
2⃣ Stateless → No client context stored on the server.
3⃣ Cacheable → Responses must define cacheability.
4⃣ Uniform Interface → Consistent API design (URIs, methods).
5⃣ Layered System → Multiple layers (security, caching, business logic).
6⃣ Code on Demand (Optional) → Send executable code to the client.

Question 57: Can We Use TCP/IP Protocol with Web API?


By default, Web API uses HTTP (which runs over TCP/IP).
✔ However, for direct TCP/IP communication, WCF (Windows Communication Foundation) is better.
✔ Web APIs are optimized for HTTP-based communication, not raw TCP/IP.

Question 58: How is WebAPI Different from an MVC Controller?


Feature Web API MVC Controller
Purpose Build RESTful services Render HTML views
Return Type JSON/XML (default) HTML, JSON, XML
Request Handling Stateless HTTP requests Handles UI logic
Routing Attribute-based ([Route("api/...")]) Uses MVC Routes
Client Type Web/Mobile/IoT Browser-based UI
Use Web API for data services, and MVC for web applications.

Question 59: What is Content Negotiation in Web API?


Content Negotiation is a mechanism in Web API to return data in the format requested by the client
(JSON, XML, etc.).
✔ The client specifies the preferred format in the Accept header.

Question 60: WebAPI vs WCF?


Feature Web API WCF (Windows Communication Foundation)
Protocol HTTP (REST) HTTP, TCP, MSMQ, Named Pipes
Data Format JSON, XML Binary, XML, JSON
Performance Fast (Lightweight) Slower (Heavy)
Hosting IIS, Self-Hosting, Docker IIS, Windows Services
Use Case Web/Mobile APIs Enterprise apps, TCP/IP services
When to Use What?
✔ Use Web API for modern RESTful services (JSON/XML).
✔ Use WCF for complex enterprise applications needing TCP, MSMQ, or SOAP.
Question 61: WCF REST vs WebAPI REST?
Feature WCF REST Web API REST
Protocol Supports HTTP, TCP, MSMQ, Named Pipes Only HTTP
Configuration Requires config-heavy setup Lightweight, convention-based
Performance Slower due to SOAP/XML overhead Faster, optimized for REST
Hosting IIS, Windows Services, Self-hosting IIS, Docker, Self-hosting
Serialization Custom serialization needed Built-in JSON, XML support
Best for Enterprise apps, legacy SOAP-based services Modern RESTful APIs
When to Use What?
✔ Use Web API for lightweight, RESTful HTTP services.
✔ Use WCF if you need SOAP, TCP/IP, or advanced enterprise features.
Question 62: How to Return HTTP Status Codes?
Use IActionResult in ASP.NET Web API.
Common Status Codes:
✔ 200 OK → Success
✔ 201 Created → Resource created
✔ 400 Bad Request → Invalid input
✔ 401 Unauthorized → Authentication required
✔ 403 Forbidden → No permission
✔ 404 Not Found → Resource missing
✔ 500 Internal Server Error → Server issue

Question 63: Which Status Code is Returned for Errors?


Depends on the type of error:
Error Type Status Code
Invalid Request Data 400 Bad Request
Unauthorized (Missing Token) 401 Unauthorized
Forbidden (No Permission) 403 Forbidden
Resource Not Found 404 Not Found
Server Error (Unhandled Exception) 500 Internal Server Error

Question 64: How Did You Secure Your Web API?


Security Best Practices:
1⃣ JWT Authentication (Most common)
2⃣ OAuth 2.0 Authorization
3⃣ API Key Authentication
4⃣ HTTPS (SSL/TLS)
5⃣ CORS Protection
6⃣ Rate Limiting (Prevent API abuse)
7⃣ Input Validation & Logging

Question 65: How Do Current JS Frameworks Work with Web API?


React, Angular, Vue use Web API via HTTP requests (AJAX/Fetch/Axios).
✔ They use JWT tokens for authentication via HTTP headers.

Question 66: How Does Token-Based Authentication Work?


Token-based authentication uses JWT tokens instead of sessions.
Flow:
1⃣ User logs in → Sends username/password.
2⃣ Server verifies → Issues a JWT token.
3⃣ Client stores token (e.g., in LocalStorage).
4⃣ Client sends token in Authorization header for API requests.
5⃣ Server validates token before processing requests.

Question 67: Why is it Called a JWT Token?


JWT stands for "JSON Web Token".
✔ It is a compact, URL-safe token format.
✔ "Token" represents user authentication details.

Question 68: Explain the 3 Sections of a JWT Token?


JWT has three parts (Header, Payload, Signature).

Part Description Example Data


Header Defines algorithm & token type { "alg": "HS256", "typ": "JWT" }
Payload Contains user data (claims) { "userId": "1234", "role": "User", "exp": 1702920000 }
Signature Ensures token integrity HMACSHA256(base64(header) + base64(payload), secret)

Question 69: What are Identity and Claims?


Identity → Represents the authenticated user.
Claims → Key-value pairs that store user details (ID, role, email).
✔ Claims help in role-based authorization (Admin, User, etc.).

Question 70: Authentication vs Authorization?


Feature Authentication Authorization
Definition Verifying who the user is Checking what the user can access
Example "Is this user valid?" "Does this user have Admin access?"
Process User logs in using credentials User is granted specific permissions
Handled By JWT, OAuth, Identity Server Role-Based (RBAC), Claims-Based Policies
Example:
✔ Authentication: User logs in with username/password.
✔ Authorization: User is allowed to access Admin Panel (if role = "Admin").

Question 71: Claims vs Roles?


Roles and Claims are used in authorization, but they serve different purposes.
Feature Roles Claims
Definition A predefined group/category of users A key-value pair that stores user-specific data
Example "Admin", "User", "Manager" {"Department": "HR"}, {"CanEdit": "true"}
Granularity Broad, groups users into categories Fine-grained, stores specific permissions
Usage User.IsInRole("Admin") User.HasClaim("CanEdit", "true")
✔ Use Roles for broad permissions.
✔ Use Claims for fine-grained control.

Question 72: Principal vs Identity?


Principal and Identity are key security objects in ASP.NET.
Feature Identity Principal
Definition Represents who the user is Represents the user + their permissions
Example "John Doe" (user's identity) "John Doe" is an "Admin" (roles, claims, etc.)
Class ClaimsIdentity ClaimsPrincipal
Usage Stores username, ID, authentication type Stores roles, claims, authentication status

✔ Principal = Who you are + what you can do

Question 73: Can We Put Critical Information in JWT Token?


NO! Never put sensitive data (passwords, credit cards, etc.) in JWT tokens.
✔ JWTs are Base64-encoded, not encrypted → Anyone can decode them.
✔ Instead, store only user ID & role in JWT.
✔ Use encrypted cookies or database for critical data.

Question 74: How to Create JWT Token in MVC?


Use System.IdentityModel.Tokens.Jwt to generate tokens.
Example: Generate JWT Token in .NET Core
csharp
CopyEdit
public string GenerateJwtToken(string userId)
{
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-secret-key"));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

var claims = new[]


{
new Claim(ClaimTypes.NameIdentifier, userId),
new Claim(ClaimTypes.Role, "Admin") // Role-based access
};

var token = new JwtSecurityToken(


issuer: "yourdomain.com",
audience: "yourdomain.com",
claims: claims,
expires: DateTime.UtcNow.AddHours(1),
signingCredentials: credentials
);

return new JwtSecurityTokenHandler().WriteToken(token);


}
✔ Call this method during login to generate a token.

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 76: Where is Token Checked in ASP.NET MVC?


✔ Token is validated inside JWT Middleware (AddJwtBearer).
✔ It checks the token's signature, expiration, and claims.
✔ Token is checked before the controller is executed.

Question 77: What is the Use of Authorize Attribute?


Restricts access to authenticated users.
[Authorize] // Only logged-in users can access
public IActionResult SecurePage()
{
return View();
}
✔ Can also restrict by roles:
csharp
CopyEdit
[Authorize(Roles = "Admin")]
public IActionResult AdminPage()
{
return View();
}

Question 78: How Did You Implement JWT Token Security?


Steps to Secure an API with JWT:
1⃣ User logs in → Server validates credentials.
2⃣ Server generates JWT token with user ID & role.
3⃣ Token is returned to the client.
4⃣ Client stores token (e.g., localStorage, sessionStorage).
5⃣ Client sends token in every API request (Authorization: Bearer <token>).
6⃣ Server validates token before allowing access.

Question 79: How Do We Send Tokens from Client Side?


Clients send JWT tokens in the Authorization header.
Example (JavaScript Fetch API):
javascript
CopyEdit
fetch("https://api.example.com/products", {
method: "GET",
headers: {
"Authorization": "Bearer your-jwt-token",
"Content-Type": "application/json"
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("Error:", error));
✔ Every API request must include the token.

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;

Question 81: How to Improve UX in Mobile Apps to Avoid Re-Login?


Best Practices to Keep Users Logged In:
1⃣ Use Refresh Tokens to re-authenticate users without asking for login.
2⃣ Extend Session Duration by updating the token expiration on each request.
3⃣ Secure Token Storage → Use Secure Storage (iOS Keychain / Android EncryptedSharedPrefs) instead
of localStorage.
4⃣ Auto Re-login Mechanism → Detect expired access tokens and refresh them silently.
5⃣ Biometric Authentication (FaceID, Fingerprint) → Provide a seamless quick login option.
Example in Mobile Apps (React Native Secure Storage)
javascript
CopyEdit
import EncryptedStorage from 'react-native-encrypted-storage';

// Save Token Securely


await EncryptedStorage.setItem("auth_token", accessToken);

// Retrieve Token
const token = await EncryptedStorage.getItem("auth_token");

Question 82: What are Refresh Tokens?


Refresh tokens are long-lived tokens used to get new access tokens without requiring login again.
✔ They help in maintaining a user's session without prompting for credentials repeatedly.

Question 83: How Does a Refresh Token Work?


1⃣ User logs in, and the server returns two tokens:
• Access Token (short-lived, e.g., 15 min)
• Refresh Token (long-lived, e.g., 7 days)
2⃣ When the access token expires, the app sends the refresh token to get a new access token.
3⃣ If the refresh token is valid, a new access token is issued without asking the user to log in.
Refresh Token Flow:
Client → Server: Login (username + password)
Server → Client: Access Token + Refresh Token
Client → Server: Request with Access Token
Server → Client: Response
(Access Token expires)
Client → Server: Send Refresh Token
Server → Client: New Access Token

Question 84: Access Tokens vs Refresh Tokens?


Feature Access Token Refresh Token
Purpose Used to access APIs Used to get a new Access Token
Lifetime Short-lived (e.g., 15-60 min) Long-lived (e.g., 7-30 days)
Stored in? Memory or Secure Storage Secure Storage
Sent with Requests? Yes, in Authorization Header No, only used when needed
Security Risk? Exposed in API calls Less exposed, but must be protected

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 87: How to Extract Principal from a Token?


Use JwtSecurityTokenHandler to extract claims.

Question 88: Best Practices to Store Tokens on Client Side?


✔ DO:
Store Access Tokens in Memory (not persistent).
Store Refresh Tokens in Secure Storage (e.g., Keychain, EncryptedSharedPrefs).
Use HTTP-Only Secure Cookies (prevents JavaScript access).
DON'T:
Never store tokens in localStorage (vulnerable to XSS).
Avoid saving Refresh Tokens in JS-accessible storage.
Best Approach:
✔ Access Token → Store in Memory
✔ Refresh Token → Store in Secure Cookies or Secure Storage

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

Question 90: What is OAuth and OpenID?


OAuth 2.0 = Authorization (Who can access what?)
OpenID Connect (OIDC) = Authentication (Who is the user?)
Feature OAuth 2.0 OpenID Connect
Purpose Grants access to resources Authenticates users
Use Case Login with Google/Facebook Identity verification
Token Type Access Token ID Token
Standardized? Yes Extends OAuth 2.0
✔ OAuth → Used for API access
✔ OpenID Connect → Used for login and user identity

Question 91: When to Use OAuth vs OpenID?


✔ Use OAuth when a user needs to access an API (e.g., Google Drive).
✔ Use OpenID Connect when a user needs to log in (e.g., "Login with Google").

Question 92: What is Identity Server?


Identity Server is an OpenID Connect & OAuth 2.0 server used for authentication & authorization.
✔ It allows Single Sign-On (SSO).
✔ Supports JWT, OAuth2, and OpenID.
Example Use Case:
• A company with multiple apps uses Identity Server to authenticate users once, avoiding multiple
logins.

Question 93: How to Achieve Single Sign-On (SSO)?


✔ Use Identity Server 4 (or other OpenID providers).
✔ Use OAuth2 + OpenID Connect.
✔ Store the token in a central authentication server.
Example:
• Login once → Access multiple applications without logging in again.

Question 94: What are Scopes in Identity Server?


Scopes define what data or actions a client application can access.
Types of Scopes:
1⃣ Identity Scopes → User-related data (e.g., profile, email).
2⃣ API Scopes → Permission to access APIs (e.g., read, write).
✔ The app requests openid profile email → The Identity Server returns the requested claims.

# Features with .NET Core Versions & Explanations


. .NET Core Version Feature Explanation
C# (Pre .NET Core, Auto-Implemented Simplifies property declaration without
3.0 .NET Framework Properties needing a backing field.
only)
Anonymous Types Allows defining object types without
explicitly specifying the type.
Lambda Expressions Introduced concise syntax for writing
anonymous methods.
Extension Methods Enables adding methods to existing types
without modifying them.
LINQ (Language- Provides a way to query collections using a
Integrated Query) SQL-like syntax.
C# (Pre .NET Core, Dynamic Type (dynamic) Enables runtime type resolution for objects.
4.0 .NET Framework
only)
Named & Optional Allows calling methods without specifying
Parameters all parameters explicitly.
COM Interoperability Improved support for interacting with COM
Enhancements components.
C# (Pre .NET Core, Async & Await Enables asynchronous programming with a
5.0 .NET Framework 4.5) cleaner syntax.
C# .NET Core 1.0 String Interpolation ($"") Allows embedding expressions inside
6.0 strings for better readability.
Null-Conditional Operator Prevents NullReferenceException by safely
(?.) accessing properties.
Expression-Bodied Shortens property and method declarations
Members using lambda syntax.
C# .NET Core 2.0 Tuples ((T1, T2)) Provides a lightweight way to return
7.0 multiple values from a method.
Pattern Matching Enables more powerful and readable
switch-case conditions.
Local Functions Allows defining helper functions inside
other methods for better encapsulation.
Ref Returns and Locals Enables returning references to variables
instead of values.
C# .NET Core 2.1 Span<T> (High- Optimizes memory access for performance-
7.2 performance memory sensitive applications.
handling)
ReadOnly Structs Prevents modification of struct members
after initialization.
C# .NET Core 3.0 Nullable Reference Types Helps prevent null reference exceptions by
8.0 enforcing null checks.
Default Interface Methods Allows interfaces to have method
implementations.
Async Streams (await Enables asynchronous iteration over data
foreach) streams.
Indices and Ranges (^ and Provides an easy way to slice arrays and
..) collections.
C# .NET 5 Record Types (record) Introduces immutable data types with built-
9.0 in value equality.
Init-only Setters (init) Allows setting properties only during object
initialization.
Top-level Statements Simplifies the Main method by removing
boilerplate code.
C# .NET 6 File-Scoped Namespaces Reduces indentation by allowing namespace
10.0 declarations without braces.
Global Using Directives Enables defining using statements globally
across files.
Struct Improvements (with Enables copying structs with modifications
keyword) similar to records.
C# .NET 7 Required Members Ensures that certain properties are
11.0 initialized when creating an object.
Generic Math Allows numeric operations on generic
(INumber<T>) types.
File-local Types Restricts type visibility to a single file,
preventing name conflicts.

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)

Aspect FCL (Framework Class Library) BCL (Base Class Library)


Definition It is a complete collection of reusable It is a subset of FCL that contains the most
classes, interfaces, and APIs provided by the fundamental classes required for core .NET
.NET framework. functionalities.
Scope Covers all libraries, including UI (Windows Contains only the core classes, such as
Forms, WPF), Web (ASP.NET), Data Collections, File I/O, Data Types, Security,
Access (ADO.NET, Entity Framework), etc. etc.
Purpose Provides all functionalities needed to build Provides core functionalities that are
applications in .NET. essential for .NET execution.
Components Includes BCL, plus UI frameworks (WPF, Includes essential classes like System,
WinForms), Web frameworks (ASP.NET), System.Collections, System.IO,
Data access (Entity Framework), etc. System.Threading, etc.
Dependency FCL includes BCL along with other BCL is the core part of the FCL and exists
specialized libraries. inside it.
Example System.Windows.Forms, System.Web, System, System.Collections.Generic,
Namespaces System.Data.SqlClient, System.IO, System.Threading.Tasks
System.Xml.Linq

What is GAC (Global Assembly Cache)?


GAC (Global Assembly Cache) is a centralized repository in Windows where .NET assemblies (DLL files)
that are shared across multiple applications are stored. It allows different applications to use the same version
of an assembly, ensuring consistency and reducing redundancy.

Key Features of GAC:


1. Shared Assemblies → Used for storing strong-named assemblies that can be accessed by multiple
.NET applications.
2. Versioning Support → Supports multiple versions of the same assembly (avoids "DLL Hell").
3. Security → Assemblies in GAC must have a strong name (signed with a public/private key).
4. Performance Optimization → Reduces memory usage as shared assemblies are loaded only once.

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#

Feature Literal Variable


Definition A fixed value that doesn’t change. A named storage location that can hold
different values.
Value Constant – Cannot change during Mutable – Can be updated.
execution.
Memory Usage Stored in code as a constant value. Allocated memory location to store values.
Declaration int x = 10; → 10 is a literal. int x = 10; → x is a variable.
Example
Types Integer (10), String ("Hello"), Boolean Defined using int, string, bool, etc.
(true), etc.
Scope & Lifetime No scope, exists directly in code. Exists within the scope of a method, class,
etc.

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

Stack vs Heap vs Static Memory


1⃣ Stack Memory (For Value Types & Local Variables)
• Stores: Local variables, method parameters, value types (int, double, char, bool, struct).
• Fast Access: Automatically managed (Last In, First Out – LIFO).
• Lifetime: Variable is removed when method exits.

2⃣ Heap Memory (For Reference Types & Objects)


• Stores: Objects, reference types (class, string, interface, array, delegate).
• Slower Access: Because Garbage Collector (GC) cleans it up.
• Lifetime: Exists until no references point to it.
p (reference) is in Stack, but new Person() (object) is in Heap.

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.

When to Use readonly?


✔ When you want to allow runtime assignment (unlike const).
✔ When you need immutable instance fields but set them dynamically in constructors.
✔ When you want static values that are set once but after runtime initialization.

Difference Between readonly and const


Feature readonly const
Value Assignment Can be assigned in constructor Must be assigned at declaration
When Compiled Runtime Compile-time
Can Change? No (after constructor) Never changes
Used with Instance & Static fields Only Static fields
Example readonly int x = 10; const int x = 10;

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.

Key Uses of this Keyword


Distinguish between class fields and method parameters when they have the same name.
Call another constructor within the same class (Constructor Chaining).
Pass the current object as a parameter to a method.
Return the current instance from a method (for method chaining).

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.

How yield Works?


• The method containing yield returns an IEnumerable<T> or IEnumerator<T>.
• The execution pauses at each yield return and resumes from there when the next element is requested.
• It helps in lazy evaluation, meaning elements are generated on demand instead of being computed all
at once.

Entity Framework (EF) - Overview


• What is Entity Framework?
• Entity Framework (EF) is an Object-Relational Mapper (ORM) for .NET applications that enables
developers to work with databases using C# objects, eliminating the need for complex SQL queries. It
simplifies database interactions by handling object-to-database mapping automatically.

• Features of Entity Framework
• Eliminates SQL Queries – Work with C# objects instead of raw SQL.
Automatic Mapping – Converts database tables to C# classes and vice versa.
Change Tracking – Detects changes in data and updates the database automatically.
Migrations – Handles database schema changes smoothly.
Supports LINQ Queries – Query databases using LINQ instead of SQL.

REST vs SOAP - Key Differences


Feature REST (Representational State Transfer) SOAP (Simple Object Access Protocol)
Protocol Uses HTTP and supports JSON, XML, etc. Uses XML over HTTP, SMTP, TCP, etc.
Data Format JSON, XML, YAML, etc. (Lightweight) Only XML (Heavy)
Flexibility More flexible and widely used in web APIs Strict protocol with rigid structure
Performance Faster (uses HTTP directly) Slower (due to XML overhead)
Security Relies on HTTPS & OAuth (external security) Built-in security via WS-Security
State Stateless – Each request is independent Stateful – Maintains session information
Use Cases Web APIs, Mobile Apps, Cloud Services Banking, Enterprise Apps, Payment Systems
Ease of Use Simple and easy to implement More complex with strict standards

Parallel LINQ (PLINQ) in C#


Parallel LINQ (PLINQ) is an extension of LINQ that enables parallel processing to improve performance on
multi-core processors. It is part of the System.Linq.Parallel namespace and automatically distributes tasks
across multiple CPU cores.

Why Use PLINQ?


Performance Boost – Uses multiple CPU cores for parallel execution
Automatic Load Balancing – Distributes workload efficiently
Better for CPU-Intensive Tasks – Suitable for data processing, calculations, etc.
Easy to Implement – Just add .AsParallel() to LINQ queries
When to Use PLINQ?
Large data sets that need fast processing
CPU-intensive operations like math calculations, simulations, and data aggregation
Running queries on multi-core processors
Avoid PLINQ if:
• The dataset is small (PLINQ overhead can slow it down)
• Operations are I/O-bound (Database queries, File reading, Network calls)

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

What is a Scheduler in .NET?


A scheduler in .NET is responsible for managing and executing tasks efficiently using available CPU cores.
It decides which task runs when, optimizing resource utilization.
In Task Parallel Library (TPL), the TaskScheduler class is responsible for scheduling and managing
tasks in a multithreaded environment.

What is the Global Task Queue?


• The global task queue is a shared queue where tasks are initially placed before being executed by
worker threads.
• All threads in the ThreadPool can access the global queue.
• It helps distribute work efficiently across multiple CPU cores.

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.

Task.Run() → Run asynchronous code.


✔ Task.Delay() → Non-blocking delay.
✔ Wait() / Result → Blocks execution (avoid in UI apps).
✔ ContinueWith() → Run a task after another task.
✔ WhenAll() / WhenAny() → Run multiple tasks concurrently.
✔ CancellationToken → Cancel running tasks.
✔ Exception Handling → Use try-catch with async/await.
Async & Await in C#
async and await are fundamental features in C# for writing asynchronous, non-blocking code. They allow
applications to remain responsive while performing long-running operations.

Why Use async and await?


Prevents blocking the UI thread (in desktop or web apps).
Improves application responsiveness.
Efficient thread management (no unnecessary thread blocking).

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.

What is Model Binding?


Model Binding in ASP.NET Core automatically maps HTTP request data (query string, form values,
headers, body, etc.) to action method parameters in a controller.

ources of Data for Model Binding


Model Binding extracts values from: 1⃣ Query String (?name=John)
2⃣ Form Data (From <input> fields in HTML forms)
3⃣ Route Values (/users/{id} → id is bound)
4⃣ Headers (Authorization: Bearer xyz123)
5⃣ Body (For complex objects from JSON or XML)
6⃣ Custom Binding Sources (e.g., fetching data from a database)

Model Binder Execution Process


1⃣ Find a matching parameter in the action method.
2⃣ Extract data from the request (Query, Form, Route, etc.).
3⃣ Convert the data to the expected type.
4⃣ Validate the data (e.g., required fields).
5⃣ Assign values to the parameter.

Built-in Model Binders in ASP.NET Core


ASP.NET Core provides default model binders for:
• Primitive types (int, string, bool, etc.)
• Complex types (custom objects)
• Collections (List, Array, Dictionary)
• DateTime parsing
• Custom objects using JSON

ASP.NET Core provides five types of filters:


Filter Type Execution Stage Use Case
Authorization Before anything runs Authentication & Authorization (e.g.,
Filter [Authorize])
Resource Filter Before and after model binding Request short-circuiting, caching, performance
optimization
Action Filter Before and after an action method Logging, validation, action execution logic
executes
Exception Filter When an unhandled exception Global error handling, exception logging
occurs
Result Filter Before and after an action result Modifying response, adding headers, caching
executes

You might also like