Skip to main content

OOP Interview Questions

Every question has a short model answer and a link to the lesson example that shows it in code. Levels: F = Fresher (0-2 yrs), M = Mid (3-5 yrs), S = Senior (6-9 yrs), A = Architect / Lead (10+ yrs).

Classes and objects

FWhat is the difference between a class and an object?concept

A class is a design that describes what something has (properties) and can do (methods). An object is one instance created from it with new. Student is a class; Aarav and Diya are objects with their own values.

FWhat is a constructor?concept

A special method with the class's name and no return type that runs once when an object is created. It sets up the object, and by requiring parameters it ensures no object exists without the values it needs, such as a student's name.

FWhat are the four pillars of object-oriented programming?concept

Encapsulation (a class protects its data and rules), inheritance (a class reuses and extends another), polymorphism (one call behaves differently for different types), and abstraction (code depends on what something does, not how).

MTwo variables refer to one object, and you change a property through one of them. What does the other see?concept

The change. Classes are reference types: assignment copies the reference, not the object, so both variables point to the same object. To get an independent copy, create a new object.

MWhy does == return false for two Student objects with identical values?concept

For classes, == compares references by default: it asks whether both variables point to the same object. Two separately created objects are different objects. Records, or overriding Equals, give value-based equality.

MHow do you create a custom exception, and why would you?coding

Create a class that inherits from Exception and passes the message to base(message), adding any extra data, such as an ErrorNumber. Callers can then catch your application's rule failures separately from system errors and react to them specifically.

SA report shows one student's name with another student's marks. The code uses two arrays. How would you fix it?scenario

The parallel arrays went out of step, probably after sorting one of them. Replace them with one class that holds the student and the mark together, such as ExamResult, and keep a single collection of those objects.

How to answer:

Explain the root cause, the object-based design, and why it removes the whole class of bug. Mention testing the report after sorting and filtering.

SWhat is a 'god class', and how do you avoid one?design

A class that knows and does too much, such as a SchoolManager with hundreds of methods for students, fees, and exams. It is hard to change and test. Split it by responsibility into smaller classes, each with its own data and the rules that use that data.

How to answer:

Give the warning signs (huge files, unrelated methods, many reasons to change), the refactoring approach, and connect it to the Single Responsibility Principle (Lesson 46).

AHow would you decide which classes go into a shared core library?design

Put the domain model and business rules that every application needs (entities, rule exceptions, interfaces) in the core library, with no dependency on UI, databases, or web frameworks. Keep presentation and infrastructure code in the projects that need them, which reference the core, never the other way round.

How to answer:

Explain dependency direction and why it matters for reuse and testing. Mention keeping the core free of Console, HTTP, and SQL so it works from an API, tests, or background jobs.

Encapsulation

FWhat is encapsulation?concept

Keeping an object's data private and offering only safe, public ways to change it, so the object enforces its own rules. A fee invoice's status can change only through RecordPayment.

FWhat do the access modifiers public, private, protected, and internal mean?concept

public: any code. private: only the same class (the default for members). protected: the class and classes that inherit from it. internal: any code in the same project (assembly).

FWhat is the difference between a field and a property?concept

A field is a variable inside a class. A property looks like a field from outside but runs code when read or written, so it can validate, calculate, or restrict access. Public data should be exposed through properties, not public fields.

MWhat is the difference between { get; }, { get; private set; }, and { get; init; }?concept

{ get; } can be set only in the constructor. { get; private set; } can be changed by the class's own methods at any time. { get; init; } can be set in the constructor or an object initializer, and is fixed afterwards.

MWhat is a class invariant? Give an example.concept

A rule that must always be true for an object. For a fee invoice: the status always matches the payments. The constructor checks the starting state and every method keeps the rule, so no sequence of calls can break it.

MWhat does 'tell, don't ask' mean?concept

Instead of asking an object for its data and applying rules outside it, tell the object what to do and let it apply its own rules, such as invoice.RecordPayment(amount). This keeps each rule in one place.

SInvoices show 'Paid' without any payments. How would you find the cause and stop it happening again?scenario

Find every code path that writes the status, such as an admin screen or a direct SQL update. Make the status private set, changed only by the payment method, and restrict direct updates in the database. Correct existing invoices through proper adjustments that leave an audit trail.

How to answer:

Cover investigation (who writes the field), the design fix (encapsulation), the database side (permissions or procedures), and data repair. Mention audit logs to find when it happened.

SShould every property be private or read-only? When is a public setter fine?design

No. Decide per property who legitimately changes it. Ids are set by data access code, simple descriptive fields may be freely editable, but values tied to rules, such as status or balance, should change only through methods.

How to answer:

Show judgment rather than a blanket rule. Give examples of each case and mention that DTOs, used only to carry data, often have public setters by design.

ABusiness rules exist both in SQL constraints and procedures and in C# classes. Is that duplication a problem?design

It is deliberate defense in depth: C# gives fast, clear feedback, and the database protects the data if any path skips the application. Keep the rules consistent with shared error numbers and tests, and decide which layer is authoritative for each rule.

How to answer:

Weigh duplication against safety. Explain which rules belong in the database (integrity) and which in code (workflow), and how to keep both in step.

Inheritance

FWhat is inheritance?concept

A class (the derived class) building on another (the base class), getting all its members and adding its own. Student : Person gets the names and FullName from Person and adds an admission number. Use it for true "is a" relationships.

FWhat does the base keyword do in a constructor?concept

: base(...) calls the base class's constructor with the given arguments, before the derived constructor's own code runs. It is required when the base class has no parameterless constructor.

FDoes C# support multiple inheritance?concept

Not for classes: a class has exactly one base class (error CS1721 otherwise). A class can implement many interfaces, which covers most needs for multiple "kinds" of behavior.

MWhat is the difference between private and protected?concept

private members are visible only inside the class itself, even derived classes cannot use them. protected members are visible to the class and every class that inherits from it, but not to outside code.

MWhat is the difference between is, as, and a cast when converting a base type to a derived type?coding

is with a pattern (if (p is Student s)) checks and converts safely. as returns null when the conversion fails. A cast (Student)p throws InvalidCastException when the object is not a Student. Prefer the is pattern.

MWhy can catch (SchoolRuleException) catch an InvalidMarkException?concept

Because InvalidMarkException inherits from SchoolRuleException, so it is one. A catch block matches the exception's type or any base type, which lets callers handle a whole family of errors at once or a specific one separately.

SA hierarchy Person > Staff > Teacher > ClassTeacher breaks when a teacher stops being a class teacher. What went wrong?scenario

A role that changes over time was modeled as a subclass, but an object cannot change its type. Replace the deep tree with one Teacher class plus data that records the role per year, such as a ClassTeachers table, and keep hierarchies shallow.

How to answer:

Identify the misuse (role as type), the fix (composition or data), and the general rule: if something can change, it is data or a role, not a subclass.

SComposition or inheritance: how do you choose?design

Inherit for true, permanent "is a" relationships, such as a guardian being a person. Use composition, holding another object, for "has a", such as an invoice having payments. Composition is more flexible, so prefer it when in doubt.

How to answer:

Give the tests ("is a" vs "has a", permanence), examples of each, and the costs of wrong inheritance: tight coupling and fragile base classes.

AThe C# model has a Person base class, but the database has separate Students, Teachers, and Guardians tables. Is that a problem?design

No. The class design shares code; the table design suits storage and queries. They may differ as long as the mapping is clear: each derived class maps to its own table, including the inherited columns. ORMs support several mapping strategies for hierarchies.

How to answer:

Explain the object-relational mismatch, the table-per-concrete-type approach used here, and the alternatives (one shared table, or a table per type) with their trade-offs.

Polymorphism

FWhat is polymorphism?concept

One call behaving differently depending on the object's real type. Calling Describe() on a Person variable runs the student, teacher, or guardian version, depending on which object it holds.

FWhat do virtual and override do?concept

virtual in the base class allows derived classes to replace a method or property. override in the derived class provides the replacement. base.Method() inside an override runs the base version too.

FWhy would you override ToString?concept

By default it returns the class name, such as SchoolApp.Core.Entities.Student. Overriding it gives a readable description, which interpolation, logging, and the debugger then use. Never put private data such as passwords in it.

MWhat is the difference between method overloading and method overriding?concept

Overloading: same name, different parameters, usually in one class, chosen at compile time. Overriding: same signature, new body in a derived class, needs virtual and override, chosen at run time from the object's real type.

MWhat is the difference between override and new on a method?concept

override replaces the base method for every caller. new hides it: callers using a base-type variable still get the base version, and only derived-type variables see the new one. Hiding is almost always a mistake; the compiler warns with CS0114 when neither keyword is used.

MWhat is the Template Method pattern?concept

A non-virtual method defines a fixed process and calls virtual (or abstract) steps that derived classes fill in. FeeNotice.Send always formats the same way, while Channel and Compose differ per channel.

SA 300-line switch on payment mode must change for every new mode. How would you refactor it?scenario

Create a base class or interface for payment modes with the varying behavior as virtual or abstract members, and one class per mode. Choose the class in one place, then call it through the base type. A new mode becomes one new class, with no edits to existing logic.

How to answer:

Describe the steps (extract behavior, one class per case, single creation point), the benefit (open for extension, closed for modification), and safety (tests per mode before removing the switch).

SWhen is creating a subclass the wrong way to handle a difference?design

When only a value differs, such as a rate or a limit: use a property set in the constructor instead. Use subclasses for different behavior, and interfaces when behavior must be swapped or combined at run time.

How to answer:

Show judgment with examples, and mention the cost of unnecessary classes: more code, deeper hierarchies, and harder changes.

AHow does polymorphism help a large system grow without breaking existing features?design

New behavior is added as new classes behind an existing base type or interface, so tested code is not edited. Only the place that chooses the implementation changes. This keeps changes small, reviewable, and low-risk, and lets teams work on different implementations independently.

How to answer:

Connect it to the Open/Closed Principle, plug-in architectures, and dependency injection in ASP.NET Core, with an SMS example such as notification channels.

Abstract classes and interfaces

FWhat is an abstract class?concept

A class marked abstract that cannot be created with new, only inherited from. It can hold shared code and abstract members without a body, which every derived class must override, such as ReportCard.FormatScore.

FWhat is an interface?concept

A contract listing members a class promises to provide, such as INotificationSender with Channel, CanReach, and Send. It has no constructors or instance fields; a class implements it with : IName and must provide every member.

FCan a class implement more than one interface?concept

Yes, any number, while having only one base class. A Teacher inherits from Person and is also an ISoftDeletable; a class could implement several capability interfaces at once.

MWhat is the difference between an abstract class and an interface, and when do you use each?concept

An abstract class can hold fields, constructors, and shared code, and a class can have only one; it models "is a" for related classes. An interface is a contract a class can implement alongside others; it models "can do". Use an abstract class for shared code, an interface for a capability with possibly unrelated implementations.

MWhat are default interface methods?concept

Since C# 8, an interface member can have a body that implementing classes inherit, such as Describe() in INotificationSender. They are reachable only through the interface type, and they let you add members to an interface without breaking existing implementations.

MWhat is abstraction in OOP?concept

Depending on what something does, not how it does it, and hiding the details. Notify knows only that a sender can reach a guardian and send a message; email servers and phone gateways stay hidden in the implementations.

SThe SMS calls a text-message provider directly from forty places, and the school wants to switch providers. What would you do?scenario

Introduce an interface such as INotificationSender, wrap the current provider in one class that implements it, and change the forty call sites to use the interface. Then the new provider is one new class plus one line of setup, and both can be tested with fakes.

How to answer:

Describe the refactoring steps safely (introduce the interface, migrate callers gradually, keep behavior identical), then the payoff: vendor independence and testability.

SShould every class have an interface?design

No. Add an interface when you need to swap implementations, fake a dependency in tests, or define a contract between teams or layers. An interface with one implementation and no such need only adds files and indirection.

How to answer:

Show judgment: name concrete reasons to add an interface and the cost of adding them everywhere. Mention that dependency injection in ASP.NET Core makes interfaces cheap where they are useful.

AHow do interfaces and abstract classes differ when a public contract must evolve over years?design

Adding an abstract member to either breaks every implementation. Adding a normal or virtual method to an abstract class, or a default method to an interface, does not. Design contracts small and stable, version them deliberately, and prefer adding new interfaces over changing widely used ones.

How to answer:

Discuss compatibility for libraries and APIs, the role of default interface methods, and strategies such as new interfaces, adapters, and versioning.

static, sealed, partial

FWhat is the difference between a static member and an instance member?concept

A static member belongs to the class and has one shared copy, called on the class name, such as SchoolRules.GetGrade(92m). An instance member belongs to each object and is called on an object, such as diya.GetAgeOn(date).

FWhat is a static class?concept

A class that holds only static members and can never be instantiated (error CS0712). It suits pure helpers and rules with no stored state, such as SchoolRules or Math.

FWhat does sealed mean on a class?concept

No other class may inherit from it; trying fails with error CS0509. Seal concrete classes that were not designed for extension, such as Student and Teacher.

MWhat is the difference between const and static readonly?concept

const is fixed at compile time and allowed only for simple types such as numbers and strings; other projects copy the value when they compile. static readonly is set once at run time and works for any type, such as DateOnly, and callers always read the current value.

MWhat are partial classes used for?concept

Splitting one class across several files that the compiler joins. The main use is generated code: a tool such as EF Core scaffolding writes one file, and your own code in another file survives regeneration.

MWhen should you avoid making a class static?concept

When it has dependencies or behavior you may want to replace, such as sending messages or reading the database. Static code cannot be swapped through an interface or faked in tests. Keep static for pure, deterministic rules.

STwo clerks received the same admission number on the first day of admissions. The number came from a static field. Explain and fix.scenario

A static field is shared by every request in the app and resets when the app restarts; with several copies of the API, each has its own counter. Concurrent requests and restarts produce duplicates. Move the counter to the database, such as a SQL SEQUENCE, protected by a unique constraint.

How to answer:

Explain the three failure modes (concurrency, restarts, multiple instances), the fix, and the safety net of a unique constraint. Mention reviewing every non-readonly static field.

SShould classes be sealed by default?design

Many teams seal concrete classes by default and unseal deliberately. Sealing documents that a class was not designed for inheritance, prevents fragile overrides, and allows small performance gains. Leave classes open only when extension is part of the design.

How to answer:

Present both views: the safety of sealing versus flexibility for library users. Mention that removing sealed later is safe, while adding it later breaks existing subclasses.

AWhere should shared, changing state live in a system that runs several copies of a web API?design

Never in static fields or memory of one instance. Durable shared state belongs in the database (sequences, rows with constraints) or a shared store such as a distributed cache; per-request state lives in objects created for that request. Static members hold only constants and pure logic.

How to answer:

Discuss scale-out, restarts, and concurrency, then the right home for each kind of state. Mention that this is why ASP.NET Core services are registered with scoped or transient lifetimes.

Enums, structs, records

FWhat is an enum, and why use one?concept

A type with a fixed list of named values, such as InvoiceStatus { Unpaid, PartiallyPaid, Paid, Cancelled }. It replaces magic strings: invalid values and typos fail the build, and editors list the valid options.

FWhat is a record in C#?concept

A type, written in one line such as record MarkEntry(int EnrollmentId, int ExamSubjectId, decimal? MarksObtained), with init-only properties, value equality, a readable ToString(), and with expressions for copies with changes.

FHow do you convert an enum to and from a string?coding

status.ToString() returns the member name, such as "PartiallyPaid". Enum.Parse<InvoiceStatus>("Paid") converts text back, and Enum.TryParse does it safely, returning false for unknown text.

MWhat is the difference between a struct and a class?concept

A struct is a value type: assignment copies the whole value, it cannot be null (unless nullable), and it cannot inherit. A class is a reference type: assignment copies a reference to one shared object. Use structs for small immutable values, classes for entities.

MWhat is the default value of an enum, and why can it be a problem?concept

0, whether or not a member has that value. If no member is 0, an unset enum field holds an undefined value, as with Gender. Make 0 a safe default, or require the value in the constructor, and use Enum.IsDefined for values from outside.

MWhat does a with expression do?coding

It creates a copy of a record (or struct) with some properties changed, leaving the original untouched: entered with { MarksObtained = 90m }. It is how you "change" immutable data.

SA report shows zero 'partial' invoices because C# used the string 'Partial' and the database stores 'PartiallyPaid'. How do you prevent this class of bug?scenario

Replace status strings with an enum whose member names match the database CHECK constraint exactly, and convert with ToString() and Enum.Parse. Typos then fail the build, and a test can check that every enum name is allowed by the constraint.

How to answer:

Explain the root cause (unchecked strings), the fix (enums matching the schema), and an automated guard (a test comparing enum names with the CHECK constraint values).

SShould entities like Student be records?design

Usually not. Entities have identity: two students with identical names and birth dates are still different people, distinguished by Id, and they change over time. Records compare by value and are meant to stay fixed, which suits DTOs, messages, and value objects.

How to answer:

Contrast identity equality with value equality, and mutability with immutability. Mention that ORMs track entities by key, which value equality can confuse.

AHow would you choose between class, struct, record, and record struct across a codebase?design

Classes for entities with identity and behavior; records for data passed between layers and compared by value; readonly record structs for tiny, frequently created values; enums for fixed option lists. Document the convention so the whole team chooses the same way.

How to answer:

Give the decision criteria (identity, mutability, size, equality semantics) and the costs of wrong choices, such as large struct copies or entities compared by value.

Model classes

FWhat is an entity (model) class?concept

A class that represents one row of a database table, with one property per column, such as Mark for the Marks table. Data access code reads rows into entities and saves entities back as rows.

FWhat does the required keyword do on a property?concept

Introduced in C# 11, it forces the property to be set in the object initializer when the object is created; otherwise the build fails with CS9035. It suits entities without constructors, such as Subject.Name.

FHow do you represent a column that allows NULL in an entity class?concept

Add ? to the type: decimal? for MarksObtained, string? for Remarks, DateOnly? for a return date. NOT NULL columns use the plain type, so the class tells callers exactly what may be missing.

MWhat is the difference between a foreign key property and a navigation property?concept

The foreign key property, such as StudentId, holds the stored Id and is always present. The navigation property, such as Student, holds the linked object and is filled only if the code loaded it, so it is nullable.

MHow do you avoid repeating audit columns in many entity classes?design

Put them in an abstract base class, such as AuditableEntity with CreatedAt, CreatedBy, UpdatedAt, and UpdatedBy, and a SoftDeletableEntity for soft-delete columns. Entities inherit what their table has.

MHow are junction tables such as StudentGuardians modeled in C#?concept

As a class with the two foreign keys, which together form the key, plus any data about the link, such as Relationship and IsPrimaryContact, and optional navigation properties to both sides. There is no separate Id.

SDiscounts of 2.50 are saved as 2. The column is DECIMAL(10,2). What do you check, and how do you prevent it?scenario

The entity property type: it is probably int, which drops the fraction. Change it to decimal, fix affected data, and add an automated test that compares every entity's property types and nullability with the database columns, so a mismatch fails the build.

How to answer:

Trace the value through the layers to find where the fraction is lost, then fix code, data, and process. Mention schema-comparison tests or scaffolding as long-term protection.

SRich entities or plain (anemic) entities: which do you prefer?design

A mix. Put rules inside entities where breaking them is expensive, such as payments and identity, so invalid objects cannot exist. Keep simple lookup tables plain, with rules in services. Fully anemic models scatter rules; fully rich models can fight data access tools.

How to answer:

Define both styles, give their trade-offs, and show judgment per entity. Mention that EF Core supports private setters and constructors, which makes rich entities practical.

AHand-written entities or entities generated from the database: what would you choose for a large system?design

For a database-first system with many tables, generate (scaffold) them so they always match the schema, and keep custom code in partial classes. Hand-write them when the domain model must differ from the tables. Either way, verify them automatically against the schema.

How to answer:

Compare effort, accuracy, and flexibility. Mention partial classes for custom code, regeneration on schema changes, and code-first migrations as the alternative where C# owns the schema.

DTOs and mapping

FWhat is a DTO?concept

A data transfer object: a simple class or record that carries exactly the data one API call or screen needs, such as StudentDto. It has no business rules and no database-only fields.

FWhy should an API not return entity classes directly?concept

Entities mirror the database and expose everything: password hashes, audit columns, soft-delete flags, and any column added later. DTOs send only what the client needs, so internal data cannot leak and database changes do not break clients.

FWhat is an extension method?concept

A static method in a static class whose first parameter has this, such as ToDto(this Student student). It can be called like an instance method, student.ToDto(), without changing the original class. Its namespace must be imported with using.

MWhy use separate DTOs for responses, create requests, and update requests?design

Each direction needs different fields: a response has an Id and readable values; a create request has no Id; an update request contains only fields that may change. One shared DTO would accept or expose fields it should not.

MWhat is over-posting (mass assignment), and how do DTOs prevent it?concept

A client adds extra fields to a request, such as a status or role, and the server saves them because it bound the request to an entity. Request DTOs contain only the allowed fields, so anything else in the JSON is ignored.

MWhat is flattening in mapping?concept

Building one simple DTO from values spread across linked entities, such as an invoice summary that includes the student's name from Enrollment.Student. Clients get a small, ready-to-show shape without knowing how tables are joined.

SA security review finds the profile endpoint returns the password hash. How do you fix it and prevent it across the codebase?scenario

Introduce a DTO with only the needed fields and map the entity to it before returning. Check all other endpoints for returned entities, add a review rule or analyzer that forbids entities in controller responses, and consider rotating credentials if hashes were exposed.

How to answer:

Cover the immediate fix, the audit of similar endpoints, prevention (rules, tests that inspect response shapes), and the incident response, such as assessing exposure.

SHand-written mapping or a mapping library such as AutoMapper?design

Hand-written mapping is explicit, compiler-checked, and easy to debug; renamed properties break the build. Libraries reduce repetitive code for many similar mappings but can silently skip properties. Choose per project size, and test mappings either way.

How to answer:

Weigh explicitness and safety against less code. Mention configuration validation in libraries and source-generated mappers as a middle ground.

AHow do DTOs help an API evolve without breaking mobile apps?design

The DTO is the public contract; the database and entities can change behind it while mapping adapts. Breaking changes to the DTO are made deliberately, with versioning, so apps already on phones keep working.

How to answer:

Explain contract stability, additive versus breaking changes, and API versioning strategies, with an example such as renaming a database column without changing the JSON.