100 OOPS Q&A

 

100 Comprehensive
C# OOPs Interview Questions & Answers

This post contains 100 curated questions designed to evaluate a C# developer's mastery of Object-Oriented Programming, ranging from core concepts to design patterns and practical project implementation.

Phase 1: Core OOPs Foundations (Basic to Intermediate)

1. What are the four pillars of OOP?

  • Encapsulation: Grouping data and methods into a single unit (class) and restricting access.

  • Abstraction: Hiding complex implementation details and showing only necessary features.

  • Inheritance: Creating new classes based on existing ones to promote code reuse.

  • Polymorphism: The ability of different objects to respond to the same method call in their own way.

2. Difference between a Class and an Object? A Class is a blueprint or template. An Object is an instance of that class that exists in memory.

3. What is Encapsulation and how is it achieved in C#? Encapsulation is "data hiding." It is achieved using access modifiers (private, protected, internal, public) and Properties (get and set accessors).

4. Explain Abstraction vs. Encapsulation. Encapsulation is about hiding the data; Abstraction is about hiding the complexity (the "how").

5. What is an Abstract Class? A class that cannot be instantiated and serves as a base for other classes. It can contain both abstract methods (no body) and concrete methods.

6. What is an Interface? A contract that defines a set of methods, properties, or events without implementation. Any class implementing it must provide the implementation.

7. Abstract Class vs. Interface?

  • Abstract Class: Can have state (fields) and implementation. Supports single inheritance.

  • Interface: Cannot have state (traditionally). Supports multiple inheritance. Use interfaces for "can-do" relationships and abstract classes for "is-a" relationships.

8. What is Polymorphism? The ability of one interface/method to behave differently based on the object type. It has two types: Static (Overloading) and Dynamic (Overriding).

9. What is Method Overloading? Having multiple methods in the same class with the same name but different signatures (parameters).

10. What is Method Overriding? Redefining a base class method in a derived class using virtual and override keywords.

11. Can we override a static method? No. Static methods belong to the class, not the instance, so they don't participate in polymorphism.

12. What is the virtual keyword? It indicates that a method or property can be overridden in a derived class.

13. What is the sealed keyword? When applied to a class, it prevents inheritance. When applied to a method, it prevents further overriding.

14. What is the base keyword? Used to access members (constructors, methods) of the parent class from within a derived class.

15. What is a Constructor? A special method called automatically when an object is created to initialize it.

16. Can a class have multiple constructors? Yes, this is called Constructor Overloading.

17. What is a Static Constructor? A constructor that runs only once before any instance is created or static members are accessed. It doesn't take access modifiers or parameters.

18. What is a Destructor (Finalizer) in C#? A method (~ClassName) used to perform cleanup before the Garbage Collector reclaims the object. Modern C# prefers IDisposable.

19. What is the this keyword? Refers to the current instance of the class.

20. Difference between Composition and Inheritance?

  • Inheritance: "Is-A" relationship (Dog is an Animal).

  • Composition: "Has-A" relationship (Car has an Engine). Composition is often preferred for flexibility.

Phase 2: C# Specific Implementations

21. What is an Interface Default Method (C# 8.0+)? Interfaces can now provide a default implementation for methods, allowing developers to add methods to interfaces without breaking existing implementations.

22. Explain the "New" keyword vs "Override".

  • override extends the base implementation (Polymorphism).

  • new (Hiding) creates a new method that hides the base method; it doesn't participate in polymorphism if the object is cast to the base type.

23. What are Extension Methods? They allow you to "add" methods to existing types without modifying the original code or using inheritance.

24. What is a Partial Class? Allows a single class definition to be split across multiple .cs files.

25. What are Auto-Implemented Properties? Properties where the compiler automatically generates a private backing field (public int Id { get; set; }).

26. What is a Record in C# 9.0+? A reference type that provides built-in functionality for encapsulating data with value-based equality.

27. Explain the "init" only setters. Used in properties to make them immutable after object initialization.

28. What is the difference between const and readonly?

  • const: Compile-time constant. Value cannot change.

  • readonly: Runtime constant. Can be assigned in the constructor.

29. What is an Inner/Nested Class? A class defined inside another class. It's often used for helper classes that shouldn't be exposed outside.

30. What is a Struct vs a Class?

  • Class: Reference type (Heap), supports inheritance.

  • Struct: Value type (Stack), no inheritance (except from interfaces).

31. When should you use a Struct instead of a Class? For small, data-centric objects that are immutable and won't be boxed frequently.

32. What is Boxing and Unboxing?

  • Boxing: Converting a value type to a reference type (object).

  • Unboxing: Converting a reference type back to a value type.

33. How does OOP relate to the using statement? The using statement relies on the IDisposable interface (Abstraction/Encapsulation) to ensure unmanaged resources are cleaned up.

34. What is Property Injection? A type of Dependency Injection where dependencies are passed through public properties rather than constructors.

35. Can you inherit from multiple classes in C#? No, C# supports single class inheritance but multiple interface implementation.

36. Why doesn't C# support multiple inheritance for classes? To avoid the "Diamond Problem" (ambiguity when two parents have the same method).

37. What is an Anonymous Type? A temporary class created by the compiler to hold data without explicitly defining a class.

38. Explain internal access modifier. The member is accessible only within the same assembly (DLL/EXE).

39. What is protected internal? Accessible within the same assembly OR from a derived class in another assembly.

40. What is private protected? Accessible within the same assembly AND only by derived classes.

Phase 3: SOLID Principles

41. What is SOLID? A set of five design principles to make software more understandable, flexible, and maintainable.

42. Single Responsibility Principle (SRP). A class should have only one reason to change.

43. Open/Closed Principle (OCP). Software entities should be open for extension but closed for modification. Achieved via Abstraction.

44. Liskov Substitution Principle (LSP). Objects of a superclass should be replaceable with objects of its subclasses without breaking the application.

45. Interface Segregation Principle (ISP). Clients should not be forced to depend on methods they do not use. (Smaller, specific interfaces).

46. Dependency Inversion Principle (DIP). High-level modules should not depend on low-level modules. Both should depend on abstractions.

47. How do you implement OCP in C#? Using abstract classes or interfaces so that new functionality can be added by creating new classes rather than editing old ones.

48. Give an example of violating LSP. Creating a Square class that inherits from Rectangle, where setting the width also changes the height, breaking the "Rectangle" expectation.

49. How does DIP differ from Dependency Injection (DI)? DIP is the principle (design goal), while DI is the technique (passing the dependency) to achieve that goal.

50. What is the "Program to an interface, not an implementation" rule? It means your variables/parameters should use the interface type (e.g., ILogger) rather than the concrete class (FileLogger).

Phase 4: OOP in Design Patterns

51. What is a Design Pattern? A proven solution to a common software design problem.

52. Name the three categories of Gang of Four (GoF) patterns. Creational, Structural, and Behavioral.

53. How does the Singleton Pattern use OOP features? Uses a private constructor (Encapsulation) and a static property to ensure only one instance exists.

54. What is the Factory Method Pattern? Defines an interface for creating an object but lets subclasses decide which class to instantiate.

55. Explain the Strategy Pattern. Defines a family of algorithms, encapsulates each one, and makes them interchangeable at runtime (Polymorphism).

56. What is the Observer Pattern? A provider (subject) maintains a list of dependents (observers) and notifies them of state changes.

57. How is the Decorator Pattern an alternative to Inheritance? It allows behavior to be added to an individual object, dynamically, without affecting the behavior of other objects from the same class.

58. What is the Adapter Pattern? Converts the interface of a class into another interface clients expect. "Wraps" an incompatible object.

59. What is the Facade Pattern? Provides a simplified interface to a complex subsystem.

60. Explain the Command Pattern. Encapsulates a request as an object, thereby letting you parameterize clients with different requests (Undo/Redo logic).

61. What is Dependency Injection? A design pattern where an object's dependencies are provided by an external entity rather than created by the object itself.

62. What are the types of DI? Constructor Injection, Property Injection, and Method Injection.

63. What is the Repository Pattern? Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects.

64. How does OOP help in the Unit of Work pattern? Encapsulates a transaction, ensuring that multiple repository operations either all succeed or all fail.

65. What is the Proxy Pattern? Provides a placeholder for another object to control access to it (e.g., Lazy loading).

66. What is the Template Method Pattern? Defines the skeleton of an algorithm in an operation, deferring some steps to subclasses.

67. Difference between Abstract Factory and Factory Method?

  • Factory Method: A single method to create one product.

  • Abstract Factory: An object that provides methods to create a family of related products.

68. What is the Bridge Pattern? Decouples an abstraction from its implementation so that the two can vary independently.

69. What is the Composite Pattern? Allows you to treat individual objects and compositions of objects uniformly (Tree structures).

70. What is the State Pattern? Allows an object to alter its behavior when its internal state changes. The object will appear to change its class.

Phase 5: Practical Project Brain & Architectural Scenarios

71. Why is global state (Static classes) often considered an "anti-pattern" in OOP? It makes unit testing difficult, creates hidden dependencies, and violates encapsulation/threading safety.

72. How would you design a "Payment Processing" system using OOP? Create an IPaymentProcessor interface. Implement concrete classes like PaypalProcessor, StripeProcessor. Use a PaymentFactory to instantiate them.

73. You have a class with 20 methods, but most clients only need 2. Which principle is violated? Interface Segregation Principle (ISP).

74. When would you prefer an Interface over an Abstract Class in a real project? When you want to provide common functionality across disparate classes that don't share a common "base" identity.

75. How does the "Composition over Inheritance" rule apply to a "Game Character" design? Instead of Mage : Character, use a Character class that has a List<IAbility>. This allows a character to learn/unlearn spells at runtime.

76. How do you handle "Optional" behavior in a base class? Avoid putting it in the base class. Use the Strategy Pattern or Decorator Pattern to add optional behavior.

77. What is "Tight Coupling" and how do you fix it? Tight coupling is when Class A directly instantiates Class B. Fix it by using Interfaces and Dependency Injection.

78. Explain "Cohesion" in the context of OOP. Cohesion refers to how closely related the functions within a class are. High cohesion (a class doing one specific thing) is desired.

79. How do you prevent "Fat Controllers" in ASP.NET Core using OOP? By moving business logic into Service classes (Encapsulation) and using Dependency Injection.

80. What is a "God Object" and why is it bad? A class that knows too much or does too much. It's a violation of SRP and makes maintenance a nightmare.

81. How does the "Law of Demeter" apply to C#? A method should only call methods on its own class, its parameters, or objects it created. Don't do customer.Order.Details.LineItem.Price.

82. Why use Virtual methods for Unit Testing? Mocking frameworks (like Moq) need to override methods to create "Mocks." If a method isn't virtual (or part of an interface), it's harder to test.

83. How would you refactor a long switch statement that checks types? Replace it with Polymorphism. Create a base class/interface and let each "case" be its own class implementation.

84. What is the benefit of making a class sealed by default? It provides a slight performance boost and prevents other developers from accidentally breaking logic via inheritance.

85. What is "Fragile Base Class" problem? When a change in a base class unexpectedly breaks the functionality of derived classes.

86. How do you implement "Deep Copy" vs "Shallow Copy"?

  • Shallow: MemberwiseClone(). Copies values/references.

  • Deep: Manually create new instances of all reference-type members or use Serialization.

87. How does the "Mediator" pattern help in microservices or CQRS? It encapsulates how a set of objects interact, reducing direct dependencies between them (e.g., MediatR library in C#).

88. What is "Anemic Domain Model"? A domain model where classes contain only data (properties) and no logic. Often considered an anti-pattern in pure DDD (Domain Driven Design).

89. How do you implement the "Plugin Architecture" in C#? Define interfaces in a shared DLL. Use Reflection or Assembly.Load to load external DLLs that implement those interfaces at runtime.

90. Explain "Dry" (Don't Repeat Yourself) vs "Wet" (Write Everything Twice). OOP promotes DRY through Inheritance, Mixins (Extension methods), and Abstraction.

91. How would you design a logging system that logs to File, Console, and Database? ILogger interface with Log(string message). Concrete classes for each. A CompositeLogger can hold a list of ILogger to log to all simultaneously.

92. What is the "Chain of Responsibility" pattern? Passing a request along a chain of handlers. Each handler decides either to process the request or pass it to the next handler.

93. What are "Value Objects"? Objects that are defined by their attributes rather than a unique identity (e.g., Money, Address). Usually implemented as structs or records.

94. How do you handle circular dependencies in OOP? Refactor the shared logic into a third class or use an Interface to break the direct link.

95. What is the difference between "Association", "Aggregation", and "Composition"?

  • Association: General relationship.

  • Aggregation: "Has-A" where the child can exist without the parent (Department/Teacher).

  • Composition: "Has-A" where the child cannot exist without the parent (House/Room).

96. Why is it bad to throw exceptions in a Constructor? It can leave the object in a partially initialized state, making cleanup difficult and leading to resource leaks.

97. How does the "Double Dispatch" technique work? A way to achieve polymorphism on two objects simultaneously (e.g., Visitor Pattern).

98. What is a "Mixin" and how is it simulated in C#? A way to add functionality to a class without inheritance. Simulated using Interfaces combined with Extension Methods.

99. How would you design a "Undo/Redo" feature? Using the Command Pattern. Store a stack of Command objects that have Execute() and UnExecute() methods.

100. What is the most important rule of OOP? Encapsulate what varies. Identify the parts of your application that change and separate them from the parts that stay the same.

No comments: