OOP Interview Questions & Answers – Quick Revision
Format: Short Answer → Key Points → C# Example (where useful)
Priority: 🔴 Must Know | 🟡 Important | 🟢 Nice to Know
Group 1: OOP Fundamentals
1. 🔴 What is Object-Oriented Programming (OOP), and what are its four main pillars?
Answer: OOP is a programming approach that organizes code using classes and objects, improving reusability, maintainability, and scalability.
Four Pillars:
-
Encapsulation: Protects data through controlled access.
-
Abstraction: Hides implementation details.
-
Inheritance: Reuses and extends existing functionality.
-
Polymorphism: Allows multiple implementations of the same operation.
Key Points:
-
Models real-world entities.
-
Reduces code duplication.
-
Supports modular, maintainable applications.
2. 🔴 What is the difference between a class and an object in C#?
Answer: A class is a blueprint defining properties and methods. An object is an instance of that class created at runtime.
class Employee { public string Name { get; set; } }
Employee emp = new Employee { Name = "John" };
Key Points:
-
Class = Definition; Object = Instance.
-
Multiple objects can be created from one class.
-
Each object maintains its own instance data.
3. 🔴 What are the advantages of OOP over procedural programming?
Answer: OOP organizes code around objects, while procedural programming organizes code around functions and procedures.
Key Points:
-
Reusability: Through inheritance and composition.
-
Maintainability: Changes can be isolated within classes.
-
Security: Encapsulation restricts access to data.
-
Extensibility: Polymorphism supports new implementations.
-
Testability: Interfaces enable mocking and unit testing.
4. 🔴 What is the difference between a class, struct, and record in C#?
|
Feature |
Class |
Struct |
Record |
|---|---|---|---|
|
Type |
Reference |
Value |
Reference by default |
|
Equality |
Reference by default |
Value |
Value |
|
Inheritance |
Supported |
No class inheritance |
Supported for record classes |
|
Typical use |
Services, entities |
Small values |
Immutable data models, DTOs |
class Employee { }
struct Point { public int X, Y; }
record Person(string Name, int Age);
Key Points:
-
classis a reference type. -
structis a value type. -
recordprovides value-based equality and convenient immutable-style data modeling. -
record structis also supported and is a value type.
5. 🔴 What is the difference between value types and reference types in C#?
Answer: Value types directly contain their data, while reference-type variables hold references to objects.
|
Value Type |
Reference Type |
|---|---|
|
Stores actual value |
Holds object reference |
|
Assignment copies value |
Assignment copies reference |
|
Examples: |
Examples: |
|
Can be allocated inline or on stack |
Objects usually allocated on managed heap |
int a = 10; int b = a; b = 20; // a remains 10
Key Points:
-
Changes to copied value types do not affect the original.
-
Two references can point to the same object.
-
Memory location depends on context, not simply type category.
6. 🟡 What is the difference between an object, reference, and instance?
Answer:
-
Object: An entity containing data and behavior.
-
Instance: A specific object created from a class.
-
Reference: A value used to access an object.
Employee emp1 = new Employee();
Employee emp2 = emp1;
Key Points:
-
emp1andemp2refer to the same object. -
Modifying that object through either reference affects the same instance.
7. 🟡 What are the different types of classes available in C#?
Answer: Common class categories include:
-
Concrete class: Can be instantiated.
-
Abstract class: Cannot be instantiated directly.
-
Sealed class: Cannot be inherited.
-
Static class: Contains only static members.
-
Partial class: Defined across multiple declarations.
-
Generic class: Works with type parameters.
-
Nested class: Declared inside another class.
Key Point: Choose the class type based on inheritance, instantiation, and reusability requirements.
Group 2: Encapsulation
1. 🔴 What is encapsulation, and how is it implemented in C#?
Answer: Encapsulation combines data and methods within a class while restricting direct access to internal data.
private decimal _balance;
public decimal Balance => _balance;
Key Points:
-
Implemented using access modifiers, properties, and methods.
-
Protects internal state from uncontrolled modification.
-
Allows validation before updating data.
-
Example: Bank balance updated only through
Deposit()orWithdraw().
2. 🔴 What are access modifiers in C#?
|
Modifier |
Accessibility |
|---|---|
|
|
Anywhere |
|
|
Containing type only |
|
|
Containing class and derived classes |
|
|
Same assembly |
|
|
Same assembly OR derived classes elsewhere |
|
|
Containing/derived classes within same assembly |
Key Points:
-
Default class member accessibility is
private. -
Default top-level class accessibility is
internal. -
Prefer minimum required accessibility.
3. 🔴 What is the difference between fields and properties in C#?
Answer: A field directly stores data, while a property provides controlled access to data through accessors.
private decimal _salary; // Field
public decimal Salary { get; set; } // Property
Key Points:
-
Fields are typically private.
-
Properties support
get,set, andinit. -
Properties can include validation or computed values.
-
Auto-properties can use compiler-generated backing fields.
4. 🔴 What is the difference between encapsulation and abstraction?
|
Encapsulation |
Abstraction |
|---|---|
|
Hides/protects internal data |
Hides implementation complexity |
|
Controls access |
Exposes essential functionality |
|
Uses access modifiers/properties |
Uses interfaces/abstract classes |
Key Points:
-
Encapsulation focuses on data protection.
-
Abstraction focuses on implementation hiding.
-
Example: ATM hides internal transaction processing (abstraction) and protects account balance (encapsulation).
5. 🟡 What are auto-implemented properties, read-only properties, and init properties?
Answer:
-
Auto-property: Compiler generates the backing field.
-
Read-only property: No publicly available setter.
-
Init property: Can be assigned during object initialization but not normally afterward.
public string Name { get; set; }
public int Id { get; }
public string City { get; init; }
Key Points:
-
get; set;allows reading and writing. -
get;can be assigned inside the constructor. -
init;supports initialization-time assignment.
6. 🟡 How does encapsulation help with data security, validation, and maintainability?
Answer: Encapsulation restricts direct modification and ensures data changes follow defined business rules.
Key Points:
-
Security: Prevents unrestricted access to internal state.
-
Validation: Rejects invalid values.
-
Maintainability: Internal implementation can change without affecting callers.
-
Data Integrity: Ensures consistent business rules.
Example: A bank account rejects withdrawals exceeding available balance.
Group 3: Abstraction
1. 🔴 What is abstraction, and how is it implemented in C#?
Answer: Abstraction hides implementation details and exposes only essential functionality.
Implementation: Interfaces and abstract classes.
interface IPayment { void Pay(); }
class CardPayment : IPayment { public void Pay() { } }
Key Points:
-
Reduces complexity.
-
Supports loose coupling.
-
Allows implementations to change without affecting consumers.
2. 🔴 What is an abstract class, and when should you use it?
Answer: An abstract class cannot be instantiated directly and can contain both abstract and implemented members.
abstract class Account { public abstract void CalculateInterest(); }
Key Points:
-
Used when related classes share common behavior or state.
-
Can contain constructors, fields, and virtual methods.
-
Derived concrete classes must implement inherited abstract members.
-
Example: Savings and Current accounts sharing common banking logic.
3. 🔴 What is an interface, and why is it used?
Answer: An interface defines a contract that implementing classes must satisfy.
interface IRepository { void Save(); }
class SqlRepository : IRepository { public void Save() { } }
Key Points:
-
Supports loose coupling and abstraction.
-
Enables multiple implementations.
-
Supports Dependency Injection and unit testing.
-
A class can implement multiple interfaces.
4. 🔴 What is the difference between an abstract class and an interface?
|
Abstract Class |
Interface |
|---|---|
|
Can contain instance fields |
Cannot contain instance fields |
|
Can have constructors |
Cannot have instance constructors |
|
Supports shared state |
Defines capabilities/contracts |
|
Single class inheritance |
Multiple interfaces supported |
|
Can contain abstract/concrete methods |
Can contain abstract/default methods |
Key Points:
-
Abstract class = Shared base behavior and state.
-
Interface = Contract.
-
Use interfaces for loosely coupled application services.
5. 🔴 Can an abstract class contain constructors, fields, properties, and implemented methods?
Answer: Yes. Abstract classes can contain all these members, including virtual and non-abstract methods.
abstract class Account {
protected Account() { }
public virtual void Display() { Console.WriteLine("Account"); }
}
Key Points:
-
Constructors initialize base-class state.
-
Concrete methods provide reusable functionality.
-
Virtual methods can optionally be overridden.
-
Abstract methods require implementation by concrete derived classes.
6. 🔴 Can a class implement multiple interfaces and inherit multiple classes?
Answer: A C# class can implement multiple interfaces but inherit only one direct base class.
class PaymentService : BaseService, ILogger, IDisposable { /* Implement members */ }
Key Points:
-
Multiple class inheritance is not supported.
-
Multiple interface implementation is supported.
-
Helps avoid ambiguity associated with multiple base classes.
7. 🟡 Can interfaces contain method implementations in modern C#?
Answer: Yes. C# 8 introduced default interface methods, allowing interfaces to provide implementations.
interface ILogger {
void Log() => Console.WriteLine("Default Log");
}
Key Points:
-
Helps extend interfaces without forcing existing implementations to change.
-
Default methods are generally accessed through interface references.
-
Interfaces still cannot hold instance fields.
8. 🟡 Can an abstract class implement an interface without implementing all its members?
Answer: Yes. An abstract class may leave interface members for derived concrete classes to implement.
interface ITask { void Execute(); }
abstract class TaskBase : ITask { public abstract void Execute(); }
Key Points:
-
Abstract classes can defer implementation.
-
Concrete derived classes must satisfy the remaining contract.
9. 🟡 What are explicit and implicit interface implementations?
Answer:
-
Implicit: Interface method is implemented as a public class method.
-
Explicit: Interface method is implemented using the interface name.
public void Save() { } // Implicit
void IRepository.Save() { } // Explicit
Key Points:
-
Explicit implementation is accessed through the interface.
-
Useful when interfaces contain conflicting method names.
-
Implicit implementations are directly accessible through the class.
10. 🟡 When would you choose an interface instead of an abstract class in a real project?
Answer: Choose an interface when multiple unrelated classes need the same contract without shared implementation or state.
Key Points:
-
Interface:
IEmailService,IPaymentService,IRepository. -
Abstract class: Common behavior shared by related account types.
-
Interfaces are generally preferred for DI and unit testing.
Group 4: Inheritance
1. 🔴 What is inheritance, and why is it used in C#?
Answer: Inheritance allows a derived class to reuse and extend the functionality of a base class.
class Employee { public string Name { get; set; } }
class Manager : Employee { }
Key Points:
-
Promotes code reuse.
-
Supports polymorphism.
-
Represents an IS-A relationship.
-
Derived classes inherit accessible base members.
2. 🔴 What types of inheritance are supported in C#?
Answer:
-
Single inheritance
-
Multilevel inheritance
-
Hierarchical inheritance
-
Multiple interface implementation
Key Points:
-
Multiple class inheritance is not supported.
-
Hybrid inheritance patterns can be achieved using interfaces.
3. 🔴 Why does C# not support multiple class inheritance?
Answer: C# avoids multiple class inheritance to prevent ambiguity and complexity when multiple base classes define conflicting behavior.
Key Points:
-
Avoids diamond-problem-style ambiguity.
-
Simplifies inheritance hierarchies.
-
Multiple interfaces provide contract flexibility.
4. 🔴 What is the difference between inheritance and composition?
|
Inheritance |
Composition |
|---|---|
|
IS-A relationship |
HAS-A relationship |
|
Extends a base class |
Uses another object |
|
Stronger coupling |
Usually looser coupling |
|
Supports overriding |
Supports delegation |
Key Points:
-
Inheritance:
Manager : Employee. -
Composition:
OrderServiceusesIPaymentService. -
Prefer composition when behavior should be replaceable independently.
5. 🔴 What is the purpose of the base keyword?
Answer: base accesses base-class members and invokes base-class constructors.
public Manager(string name) : base(name) { }
base.Display();
Key Points:
-
Calls a base constructor.
-
Accesses overridden or hidden base members.
-
Useful for reusing common behavior.
6. 🔴 What happens when a derived class and base class have constructors?
Answer: Base-class constructor execution occurs before the derived-class constructor body.
Key Points:
-
base(...)selects the base constructor. -
If omitted, C# attempts to call an accessible parameterless base constructor.
-
Compilation fails if no suitable base constructor exists.
7. 🔴 What is the difference between virtual, override, and new keywords?
|
Keyword |
Purpose |
|---|---|
|
|
Allows derived classes to override |
|
|
Replaces inherited virtual behavior |
|
|
Hides inherited member |
public virtual void Show() { }
public override void Show() { }
Key Points:
-
overridesupports runtime polymorphism. -
newhides rather than overrides. -
Virtual dispatch uses the runtime object type.
8. 🟡 What is method hiding, and how does it differ from method overriding?
Answer: Method hiding creates a new member with the same name, while overriding changes inherited virtual behavior.
Key Points:
-
new: Member selection depends on reference type. -
override: Virtual implementation depends on runtime object type. -
Use overriding for polymorphic behavior.
9. 🟡 Can private, static, and sealed methods be overridden?
Answer: No.
Key Points:
-
private: Not accessible for overriding. -
static: Belongs to the type, not an instance. -
sealed override: Prevents further overriding. -
Only inherited virtual, abstract, or override methods that are not sealed can be overridden.
10. 🟡 What is a sealed class, and when should you use it?
Answer: A sealed class prevents other classes from inheriting it.
sealed class SecurityToken { }
Key Points:
-
Prevents unintended inheritance.
-
Useful when behavior must not be extended.
-
stringis an example of a sealed class.
11. 🟡 What is the constructor and destructor execution order in inheritance?
Answer: Constructor bodies execute from base to derived. Finalizers, when executed, run derived cleanup before base cleanup.
Key Points:
-
Base constructor executes first.
-
Derived constructor body executes afterward.
-
Finalizer timing is nondeterministic.
-
Prefer
IDisposablefor deterministic resource cleanup.
Group 5: Polymorphism
1. 🔴 What is polymorphism, and what are its types in C#?
Answer: Polymorphism allows the same operation to behave differently depending on arguments or object implementation.
Types:
-
Compile-time: Method and operator overloading.
-
Runtime: Method overriding and interface dispatch.
Key Points:
-
Improves flexibility.
-
Reduces conditional logic.
-
Supports extensible application design.
2. 🔴 What is the difference between compile-time and runtime polymorphism?
|
Compile-Time |
Runtime |
|---|---|
|
Overloading |
Overriding |
|
Selected using compile-time types |
Uses runtime object implementation |
|
Different parameter signatures |
Virtual/abstract method dispatch |
Key Point: Overloading = Different signatures; Overriding = Different implementations.
3. 🔴 What is method overloading? Explain its rules with examples.
Answer: Method overloading defines multiple methods with the same name but different parameter signatures.
int Add(int a, int b) => a + b;
double Add(double a, double b) => a + b;
Key Points:
-
Parameter count, types, or order must differ.
-
Return type alone cannot distinguish overloads.
-
Implements compile-time polymorphism.
4. 🔴 What is method overriding? Explain using virtual and override.
Answer: Method overriding allows a derived class to provide a new implementation of an inherited virtual method.
class Animal { public virtual void Speak() => Console.WriteLine("Animal"); }
class Dog : Animal { public override void Speak() => Console.WriteLine("Dog"); }
Key Points:
-
Base method must be overridable.
-
Derived method uses
override. -
Runtime object type determines implementation.
5. 🔴 What is the difference between method overloading and method overriding?
|
Overloading |
Overriding |
|---|---|
|
Same name, different parameters |
Same inherited method signature |
|
Inheritance not required |
Requires inheritance |
|
Compile-time resolution |
Runtime virtual dispatch |
|
No |
Uses |
6. 🔴 What happens when a base class reference points to a derived class object?
Answer: A base reference can refer to a derived object. Accessible members are determined by the reference type, while overridden virtual methods execute using the runtime type.
Animal animal = new Dog();
animal.Speak(); // Dog
Key Points:
-
Supports runtime polymorphism.
-
Derived-only members require casting.
-
Non-virtual member hiding follows reference type.
7. 🔴 What is runtime method dispatch?
Answer: Runtime method dispatch selects the appropriate overridden virtual method based on the actual object type.
Key Points:
-
Uses virtual method dispatch.
-
Enables base references to invoke derived implementations.
-
Common in interfaces and abstract classes.
8. 🟡 Can methods be overloaded by changing only their return types?
Answer: No. Return type alone is not part of the method overload signature.
Key Point: Change the parameter list to create a valid overload.
9. 🟡 Can static methods be overloaded or overridden?
Answer: Static methods can be overloaded but cannot be overridden using runtime polymorphism.
Key Points:
-
Static methods belong to the type.
-
Derived static methods may hide inherited static methods.
-
Static abstract interface members are a separate compile-time feature.
10. 🟡 What is the difference between operator overloading and method overloading?
Answer: Operator overloading customizes operators for user-defined types, while method overloading defines methods with different parameter signatures.
Key Points:
-
Operator:
operator + -
Method:
Add(int, int)andAdd(double, double) -
Both are forms of compile-time polymorphism.
11. 🟡 What is the difference between overriding and method hiding using new?
Answer: Overriding replaces virtual behavior; hiding creates a separate member.
Key Points:
-
override: Runtime object type matters. -
new: Compile-time reference type matters. -
Prefer
overridewhen polymorphism is intended.
Group 6: Constructors, Static Members & Object Lifecycle
1. 🔴 What is a constructor, and what are the different types of constructors in C#?
Answer: A constructor initializes an object when it is created.
Types:
-
Parameterless constructor
-
Parameterized constructor
-
Copy constructor (user-defined pattern)
-
Static constructor
-
Private/protected constructor
Key Points:
-
Constructor name matches the class name.
-
Has no return type.
-
Instance constructors can be overloaded.
2. 🔴 What is the difference between a default constructor and a parameterized constructor?
Answer:
-
Default constructor: Compiler-provided parameterless constructor when applicable.
-
Parameterized constructor: Accepts arguments for initialization.
public Employee() { }
public Employee(string name) { Name = name; }
Key Points:
-
Explicit parameterless constructors are also possible.
-
Defining a parameterized constructor normally suppresses compiler generation of the default parameterless constructor.
3. 🔴 What is constructor overloading and constructor chaining?
Answer: Overloading defines multiple constructors; chaining invokes another constructor using this() or a base constructor using base().
public Employee() : this("Unknown") { }
public Employee(string name) { Name = name; }
Key Points:
-
Avoids duplicate initialization logic.
-
this()invokes another constructor in the same class. -
base()invokes a base-class constructor.
4. 🔴 What is the difference between this and base keywords?
|
|
|
|---|---|
|
Current object |
Base-class portion of object |
|
Accesses current members |
Accesses base members |
|
|
|
5. 🔴 What is a static class, and how does it differ from a normal class?
Answer: A static class cannot be instantiated and contains only static members.
static class MathHelper { public static int Square(int x) => x * x; }
Key Points:
-
Static classes cannot be inherited.
-
Normal classes can contain instance and static members.
-
Useful for stateless utility methods.
6. 🔴 What is the difference between static and instance members?
Answer: Static members belong to the type, while instance members belong to individual objects.
Key Points:
-
Static members are shared at the type level.
-
Instance members can hold separate values for each object.
-
Access static members using the class name.
7. 🟡 What is a static constructor, and when is it executed?
Answer: A static constructor initializes static state and runs automatically once per type before its first required use.
static Employee() { Console.WriteLine("Initialized"); }
Key Points:
-
No parameters or access modifiers.
-
Cannot be called explicitly.
-
Executes once per type initialization context.
8. 🟡 What is the difference between a constructor and a finalizer?
Answer: A constructor initializes an object, while a finalizer provides nondeterministic cleanup before garbage collection reclaims an eligible object.
Key Points:
-
Constructor executes during object creation.
-
Finalizer runs only if defined and not suppressed.
-
Finalizer execution is not guaranteed before process termination.
9. 🟡 What is the difference between IDisposable, Dispose(), and a finalizer?
Answer:
-
IDisposable: Contract for deterministic cleanup. -
Dispose(): Method releasing resources. -
Finalizer: Runtime-invoked fallback cleanup.
Key Points:
-
Use
usingfor automatic disposal. -
Prefer
Dispose()for database connections, streams, and similar resources. -
Finalizers are mainly relevant when directly owning unmanaged resources.
10. 🟡 Can constructors be private, protected, or static?
Answer: Yes.
Key Points:
-
private: Restricts external construction. -
protected: Allows construction through derived classes. -
static: Initializes static members automatically. -
Private constructors are useful in factory and singleton patterns.
11. 🟢 What is object initialization, and how do object initializers work?
Answer: Object initializers assign accessible fields or properties during object creation.
Employee emp = new Employee { Name = "John", Age = 30 };
Key Points:
-
Improves readability.
-
Uses constructor followed by member initialization.
-
Supports
initproperties.
Group 7: Interfaces & Advanced C# OOP
1. 🔴 What is the difference between an interface and a concrete class?
Answer: An interface defines a contract, while a concrete class provides implementations and can be instantiated.
Key Points:
-
Interface cannot be directly instantiated.
-
Concrete class can maintain state.
-
One class can implement multiple interfaces.
2. 🔴 How does interface-based programming support loose coupling?
Answer: Consumers depend on interfaces rather than specific implementations.
public OrderService(IPaymentService paymentService) { }
Key Points:
-
Implementations can be replaced.
-
Improves unit testing.
-
Reduces dependency on concrete classes.
3. 🔴 What is Dependency Injection, and how does it relate to OOP?
Answer: Dependency Injection supplies required dependencies from outside a class rather than creating them internally.
builder.Services.AddScoped<IEmployeeService, EmployeeService>();
Key Points:
-
Supports loose coupling.
-
Commonly uses interfaces.
-
ASP.NET Core provides built-in DI.
-
Main lifetimes: Transient, Scoped, Singleton.
4. 🔴 What is the difference between tight coupling and loose coupling?
Answer: Tight coupling depends directly on concrete implementations; loose coupling depends on abstractions.
Key Points:
-
Tight coupling makes changes and testing harder.
-
Loose coupling improves flexibility and maintainability.
-
Interfaces and DI help reduce coupling.
5. 🔴 How do you implement multiple interfaces in a single class?
Answer: List interfaces after the class name and implement their required members.
class ReportService : IPrintable, IExportable { /* Implement both contracts */ }
Key Points:
-
Supports multiple capabilities.
-
Avoids multiple class inheritance.
-
Explicit implementation resolves conflicting member names.
6. 🟡 What is interface segregation, and why should large interfaces be avoided?
Answer: Interface Segregation Principle says clients should not depend on methods they do not use.
Key Points:
-
Prefer smaller, focused interfaces.
-
Avoid forcing unused implementations.
-
Example: Separate
IReadableRepositoryandIWritableRepository.
7. 🟡 What is covariance and contravariance in C#?
Answer: Covariance (out) supports more-derived result types; contravariance (in) supports less-derived input types in variant generic interfaces and delegates.
IEnumerable<string> names = new List<string>();
IEnumerable<object> objects = names;
Key Points:
-
Covariance:
out T, output positions. -
Contravariance:
in T, input positions. -
Generic variance applies to reference-type conversions.
8. 🟡 What is the difference between is, as, and explicit casting?
|
Keyword |
Purpose |
|---|---|
|
|
Tests type compatibility / pattern matching |
|
|
Safe reference/nullable conversion, returns null on failure |
|
Explicit cast |
Converts or casts, may throw on failure |
if (obj is Employee emp) Console.WriteLine(emp.Name);
Employee? employee = obj as Employee;
Key Points:
-
Prefer pattern matching when type checking and accessing.
-
asavoids invalid-cast exceptions. -
Explicit casts are useful when conversion is expected to succeed.
9. 🟡 What are generic classes and generic interfaces?
Answer: Generics allow classes and interfaces to work with different data types while preserving compile-time type safety.
class Repository<T> { public T? Item { get; set; } }
interface IRepository<T> { void Add(T item); }
Key Points:
-
Promotes reusable code.
-
Reduces casting.
-
Examples:
List<T>,IEnumerable<T>.
10. 🟢 What are default interface methods, and what problems do they solve?
Answer: Default interface methods provide implementations directly inside interfaces.
Key Points:
-
Introduced in C# 8.
-
Helps evolve existing interfaces.
-
Reduces breaking changes for implementers.
Group 8: Object Class, Equality & Memory
1. 🔴 What is the object class in C#, and why is it important?
Answer: System.Object is the ultimate base type for all C# types.
Key Points:
-
Provides
ToString(),Equals(),GetHashCode(), andGetType(). -
Supports common object behavior.
-
Value types derive through
System.ValueType.
2. 🔴 What is the difference between ==, Equals(), and ReferenceEquals()?
|
Method |
Purpose |
|---|---|
|
|
Operator-based equality |
|
|
Equality based on type implementation |
|
|
Checks whether references identify the same object |
Key Points:
-
Default class equality usually compares references.
-
stringuses value equality for==. -
ReferenceEquals()always checks reference identity.
3. 🔴 What is boxing and unboxing?
Answer: Boxing converts a value type into an object representation; unboxing extracts the value type through an explicit cast.
object obj = 100; // Boxing
int value = (int)obj; // Unboxing
Key Points:
-
Boxing allocates an object.
-
Unboxing requires a compatible type.
-
Frequent boxing can affect performance.
-
Generics help avoid unnecessary boxing.
4. 🔴 What is the difference between shallow copy and deep copy?
Answer: Shallow copy duplicates top-level fields while sharing referenced nested objects. Deep copy duplicates the required nested objects as well.
Key Points:
-
Shallow copy is usually faster.
-
Deep copy provides independent mutable nested objects.
-
Important when copying complex object graphs.
5. 🟡 What is the purpose of GetHashCode()?
Answer: GetHashCode() returns a hash value used by hash-based collections.
Key Points:
-
Used by
DictionaryandHashSet. -
Equal objects must have equal hash codes.
-
Different objects can have the same hash code.
6. 🟡 Why should Equals() and GetHashCode() be overridden together?
Answer: To maintain the equality contract required by hash-based collections.
Key Points:
-
If two objects are equal, their hash codes must match.
-
Inconsistent implementations cause lookup problems.
-
Equality-relevant fields should remain stable while used as hash keys.
7. 🟡 What is the difference between MemberwiseClone() and a custom deep copy?
Answer: MemberwiseClone() creates a shallow copy, while custom deep-copy logic duplicates nested mutable objects.
Key Points:
-
MemberwiseClone()is protected. -
Shallow copies share nested references.
-
Deep copying requires explicit logic or an appropriate library.
8. 🟡 What is the difference between stack and heap memory in C#?
Answer: The stack commonly stores call frames and local data; the managed heap stores most reference-type objects.
Key Points:
-
Stack allocation is typically fast and scoped to execution.
-
Managed heap memory is reclaimed by GC.
-
Value types are not always stored on the stack.
-
Reference-type variables can themselves reside on the stack.
9. 🟢 How does the Garbage Collector manage object memory?
Answer: .NET GC automatically reclaims managed heap memory occupied by unreachable objects.
Key Points:
-
Uses generations 0, 1, and 2.
-
Reduces manual memory management.
-
Does not replace deterministic disposal.
-
IDisposablehandles timely resource cleanup.
10. 🟢 What are weak references in C#?
Answer: Weak references allow access to an object without preventing garbage collection.
Key Points:
-
Useful for certain caches.
-
Referenced objects may disappear after GC.
-
Use
WeakReference<T>.
Group 9: SOLID Principles & OOP Design
1. 🔴 What are the SOLID principles, and why are they important?
Answer: SOLID consists of five design principles that improve maintainability, flexibility, and testability.
|
Principle |
Meaning |
|---|---|
|
S – SRP |
Single Responsibility |
|
O – OCP |
Open/Closed |
|
L – LSP |
Liskov Substitution |
|
I – ISP |
Interface Segregation |
|
D – DIP |
Dependency Inversion |
Key Points:
-
Reduces tight coupling.
-
Improves code organization.
-
Supports scalable application architecture.
2. 🔴 What is the Single Responsibility Principle (SRP)?
Answer: A class should have one primary responsibility and one reason to change.
Example: OrderService handles business logic; EmailService handles notifications.
Key Points:
-
Avoid large classes with unrelated responsibilities.
-
Improves maintainability and testing.
-
Does not mean a class must contain only one method.
3. 🔴 What is the Open/Closed Principle (OCP)?
Answer: Software components should be open for extension but closed for modification.
Example: Add a new UPIPayment implementation of IPayment without modifying existing payment implementations.
Key Points:
-
Uses interfaces and polymorphism.
-
Supports new functionality with minimal changes.
-
Reduces regression risk.
4. 🔴 What is the Liskov Substitution Principle (LSP)?
Answer: Derived classes should be usable wherever their base type is expected without breaking expected behavior.
Key Points:
-
Derived classes must honor base contracts.
-
Avoid unexpected exceptions or invalid behavior.
-
Example: All
IPaymentimplementations should respect the payment contract.
5. 🔴 What is the Interface Segregation Principle (ISP)?
Answer: Clients should not depend on interface members they do not need.
Key Points:
-
Create focused interfaces.
-
Avoid large multipurpose contracts.
-
Example: Separate read and write repository interfaces when appropriate.
6. 🔴 What is the Dependency Inversion Principle (DIP)?
Answer: High-level and low-level modules should depend on abstractions rather than directly depending on each other.
Key Points:
-
Business logic depends on interfaces.
-
Infrastructure implements those interfaces.
-
Supports Clean Architecture and testability.
7. 🔴 What is the difference between Dependency Inversion and Dependency Injection?
|
Dependency Inversion |
Dependency Injection |
|---|---|
|
Design principle |
Implementation technique |
|
Depend on abstractions |
Supply dependencies externally |
|
Defines dependency direction |
Handles dependency creation/wiring |
Key Point: DIP is the principle; DI is one way to implement it.
8. 🟡 What is composition over inheritance, and why is it recommended?
Answer: Composition builds functionality by combining objects instead of inheriting behavior.
Key Points:
-
Reduces inheritance coupling.
-
Allows behavior replacement.
-
Example:
OrderServiceuses an injectedIPaymentService.
9. 🟡 What is the difference between association, aggregation, and composition?
|
Relationship |
Meaning |
|---|---|
|
Association |
General relationship between objects |
|
Aggregation |
Whole-part relationship with independent lifetimes |
|
Composition |
Strong ownership relationship with dependent lifetime |
Examples:
-
Association: Teacher–Student.
-
Aggregation: Department–Employee.
-
Composition: Order–OrderLine.
10. 🟡 How do SOLID principles improve testability and maintainability?
Answer: SOLID encourages focused responsibilities, replaceable implementations, and dependency on abstractions.
Key Points:
-
Easier unit testing.
-
Reduced regression risk.
-
Simpler code changes.
-
Better separation of concerns.
Group 10: Real-Time OOP Scenarios in ASP.NET Core
1. 🔴 How do you apply the four OOP pillars in an ASP.NET Core Web API application?
Answer:
-
Encapsulation: Private fields and controlled properties.
-
Abstraction: Service/repository interfaces.
-
Inheritance: Base controllers or shared base classes.
-
Polymorphism: Multiple implementations of a service contract.
Key Points:
-
Improves modularity and maintainability.
-
Supports Clean Architecture.
-
Makes application services easier to test.
2. 🔴 How do interfaces and Dependency Injection work together in ASP.NET Core?
Answer: Interfaces define contracts, implementations provide behavior, and DI injects the required implementation.
builder.Services.AddScoped<IOrderService, OrderService>();
public OrdersController(IOrderService service) { _service = service; }
Key Points:
-
DI container manages dependencies.
-
Supports loose coupling.
-
Simplifies unit testing with mocks.
3. 🔴 Why do we create separate Controller, Service, and Repository classes?
Answer: To separate HTTP handling, business logic, and data access responsibilities.
Controller → Service → Repository → Database
Key Points:
-
Controller handles requests/responses.
-
Service implements business rules.
-
Repository handles persistence.
-
Follows separation of concerns and SRP.
4. 🔴 How do you implement polymorphism in a real-world application?
Answer: Define a common interface or base class and provide multiple implementations.
Example: IPaymentService implemented by CardPaymentService and UPIPaymentService.
Key Points:
-
Same contract, different behavior.
-
Enables runtime selection of implementations.
-
Avoids duplicated conditional logic.
5. 🔴 How would you design multiple payment methods using interfaces and polymorphism?
Answer: Create a common payment interface and separate classes for each payment type.
interface IPayment { void Pay(decimal amount); }
class CardPayment : IPayment { public void Pay(decimal amount) { /* Process card */ } }
Key Points:
-
Add UPI, Net Banking, or Wallet implementations.
-
Resolve the appropriate strategy using a factory or DI.
-
Follows OCP and DIP.
6. 🔴 When would you choose an abstract class instead of an interface in a banking application?
Answer: Choose an abstract class when related account types share common state and reusable implementation.
Example: BankAccount provides account details and common transaction methods, while derived account types implement interest calculations.
Key Points:
-
Abstract class supports shared state and constructors.
-
Interface defines capabilities across unrelated types.
-
Avoid inheritance when no genuine IS-A relationship exists.
7. 🔴 How does Clean Architecture apply OOP and SOLID principles?
Answer: Clean Architecture separates responsibilities into layers and uses abstractions to keep business logic independent of infrastructure.
API → Application → Domain
↑
Infrastructure
Key Points:
-
Domain contains business entities/rules.
-
Application contains use cases and interfaces.
-
Infrastructure implements persistence and external services.
-
Dependencies point inward toward business logic.
8. 🟡 How do you design reusable services without tightly coupling components?
Answer: Define focused interfaces, inject dependencies, and avoid direct construction of concrete services.
Key Points:
-
Follow SRP and DIP.
-
Use constructor injection.
-
Keep business logic independent of frameworks where practical.
-
Reuse services through contracts.
9. 🟡 How would you refactor a large class that violates SRP?
Answer: Identify unrelated responsibilities and extract them into focused classes or services.
Example: Split OrderManager into OrderService, PaymentService, and NotificationService.
Key Points:
-
Separate business logic from infrastructure concerns.
-
Inject extracted services.
-
Add tests before and after refactoring.
10. 🟡 How do you write unit tests for classes that depend on interfaces?
Answer: Replace real dependencies with mocks or fakes and test the class independently.
var mock = new Mock<IOrderRepository>();
var service = new OrderService(mock.Object);
Key Points:
-
Use xUnit, NUnit, or MSTest.
-
Mock dependencies using Moq or alternatives.
-
Verify business results and dependency interactions.
-
Avoid real database calls in unit tests.
11. 🟡 How would you replace a long if-else or switch statement using polymorphism?
Answer: Use the Strategy Pattern with a common interface and separate implementations.
Example: Instead of checking payment type repeatedly, create CardPayment, UPIPayment, and WalletPayment strategies.
Key Points:
-
Reduces complex conditional logic.
-
New behavior can be added through new classes.
-
A factory or DI selects the appropriate strategy.
-
A small switch in a factory may still be reasonable.
12. 🟡 How do you decide between inheritance, composition, and Dependency Injection?
Answer: Choose based on the relationship and dependency requirements.
|
Technique |
When to Use |
|---|---|
|
Inheritance |
Genuine IS-A relationship |
|
Composition |
HAS-A relationship / reusable behavior |
|
Dependency Injection |
External dependencies and replaceable implementations |
Key Points:
-
Prefer inheritance for stable type hierarchies.
-
Prefer composition for flexible behavior reuse.
-
Use DI to supply collaborators and reduce coupling.
-
Composition and DI are often used together.
Final Interview Revision – Most Important Concepts
|
Concept |
Remember |
|---|---|
|
OOP |
Encapsulation, Abstraction, Inheritance, Polymorphism |
|
Encapsulation |
Protect internal state |
|
Abstraction |
Hide implementation complexity |
|
Inheritance |
IS-A relationship |
|
Composition |
HAS-A relationship |
|
Polymorphism |
Same contract, different behavior |
|
Overloading |
Same method name, different parameters |
|
Overriding |
Derived implementation of virtual method |
|
Interface |
Contract and loose coupling |
|
Abstract Class |
Shared behavior and state |
|
DI |
Inject dependencies externally |
|
DIP |
Depend on abstractions |
|
SRP |
One reason to change |
|
OCP |
Extend without modifying existing behavior |
|
LSP |
Derived types honor base contracts |
|
ISP |
Small, focused interfaces |
|
SOLID |
Maintainable, extensible, testable design |
|
Clean Architecture |
Business logic independent of infrastructure |
Interview preparation priority: Focus first on all 🔴 questions, especially interfaces vs abstract classes, polymorphism, inheritance, DI, SOLID, and real-time ASP.NET Core scenarios. These are particularly important for Senior .NET Developer and Technical Lead interviews.