Kiyosoft - Interview Preparation
Table of Contents
OOP Concepts — Senior Interview Guide
Level: senior (12–15+ years) · C# / .NET 8
Every worked example comes in three business domains — Insurance, Employee (HR) and Student (LMS). Use the domain filter above to show just one.
Fundamentals
1. What is object-oriented programming, and what problem does it actually solve?
Answer
OOP organises a program around types that own their data and the rules that govern it, rather than around procedures that push shared data structures between them. The value is not "modelling the real world" — it is locality of invariants: if a rule about Premium can only be violated by code inside Policy, then reviewing Policy is enough to trust the rule. Procedural code puts that rule everywhere the data travels, so correctness becomes a whole-codebase property. Every other benefit people cite (reuse, polymorphism, extensibility) is downstream of that.
Example — Insurance
A policy's premium may never go negative, and a lapsed policy may never be re-priced. Procedurally that check is copy-pasted into every caller; as a type it exists once.
public sealed class Policy
{
public PolicyStatus Status { get; private set; }
public decimal Premium { get; private set; }
public void Reprice(decimal newPremium)
{
if (Status == PolicyStatus.Lapsed)
throw new InvalidOperationException("A lapsed policy cannot be repriced.");
if (newPremium < 0)
throw new ArgumentOutOfRangeException(nameof(newPremium));
Premium = newPremium;
}
}
There is no code path that produces a negative premium, because there is no setter.
Example — Employee
Leave balance must never be driven below zero, and approvals must not exceed the remaining balance.
public sealed class LeaveBalance
{
public int RemainingDays { get; private set; }
public void Consume(int days)
{
if (days <= 0) throw new ArgumentOutOfRangeException(nameof(days));
if (days > RemainingDays)
throw new InvalidOperationException($"Only {RemainingDays} day(s) remain.");
RemainingDays -= days;
}
}
Example — Student
A student cannot be enrolled twice in the same course, and cannot exceed the credit cap for a semester.
public sealed class Semester
{
private readonly List<Enrolment> _enrolments = new();
public IReadOnlyList<Enrolment> Enrolments => _enrolments;
public int CreditCap { get; }
public void Enrol(Course course)
{
if (_enrolments.Any(e => e.CourseId == course.Id))
throw new InvalidOperationException("Already enrolled in this course.");
if (_enrolments.Sum(e => e.Credits) + course.Credits > CreditCap)
throw new InvalidOperationException("Credit cap exceeded.");
_enrolments.Add(new Enrolment(course.Id, course.Credits));
}
}
2. Class, object, instance, reference — what is actually different at runtime?
Answer
A class is a type descriptor: at runtime it exists once, as a MethodTable (what typeof(Policy) hands you), holding the layout, the method dispatch table and the static fields. An object (an instance) is a block of memory on the managed heap carrying a header, a pointer to that method table, and the instance fields. A reference is a variable holding the address of that block. Two references can name one object; two objects of the same class always share one method table.
Example — Insurance
var a = new Policy("MTR-001");
var b = a; // same object, second reference
var c = new Policy("MTR-001"); // different object, equal content
Console.WriteLine(ReferenceEquals(a, b)); // True
Console.WriteLine(ReferenceEquals(a, c)); // False
Console.WriteLine(ReferenceEquals(a.GetType(), c.GetType())); // True — one shared type object
Example — Employee
var emp = new Employee("E-4471");
var alias = emp;
alias.Promote("Principal Engineer");
Console.WriteLine(emp.Title); // "Principal Engineer" — one object, seen through two names
Aliasing is why exposing a mutable object from a getter leaks control of your own state.
Example — Student
Student.UniversityCode = "KIYO"; // static: one slot on the type, not per instance
var s1 = new Student("S-1001");
var s2 = new Student("S-1002");
// s1 and s2 have separate Name/Id fields but read the same UniversityCode.
3. Encapsulation — what does it mean beyond "make fields private"?
Answer
Encapsulation is hiding representation so that it can change without breaking callers, and hiding state transitions so that they can only happen through vetted operations. Private fields with public get/set properties for each one satisfies neither: it publishes the representation field-by-field and lets any caller drive the object into an invalid state. Real encapsulation means the public surface is expressed in operations of the domain, and internal collections are never handed out mutable.
Example — Insurance
The leaky version, then the encapsulated one:
// Leaky: caller can add a coverage that breaches the sum-insured limit.
public class Policy
{
public List<Coverage> Coverages { get; set; } = new();
public decimal SumInsured { get; set; }
}
// Encapsulated: one entry point, invariant enforced, collection exposed read-only.
public sealed class Policy
{
private readonly List<Coverage> _coverages = new();
public IReadOnlyList<Coverage> Coverages => _coverages;
public decimal SumInsured { get; private set; }
public void AddCoverage(Coverage coverage)
{
if (_coverages.Sum(c => c.Limit) + coverage.Limit > SumInsured)
throw new InvalidOperationException("Coverage limits exceed the sum insured.");
_coverages.Add(coverage);
}
}
Example — Employee
A payroll run must be immutable once approved — the guard belongs inside the type, not in the controller.
public sealed class PayrollRun
{
private readonly List<PayslipLine> _lines = new();
public IReadOnlyList<PayslipLine> Lines => _lines;
public bool IsApproved { get; private set; }
public void AddLine(PayslipLine line)
{
if (IsApproved) throw new InvalidOperationException("Approved payroll is frozen.");
_lines.Add(line);
}
public void Approve() => IsApproved = true;
}
Example — Student
public sealed class Transcript
{
private readonly Dictionary<Guid, Grade> _grades = new();
// Returning the dictionary directly would let callers rewrite grades.
public IReadOnlyDictionary<Guid, Grade> Grades => _grades;
public void RecordGrade(Guid courseId, Grade grade)
{
if (_grades.ContainsKey(courseId))
throw new InvalidOperationException("Grade already recorded; use AmendGrade with a reason.");
_grades[courseId] = grade;
}
}
4. Abstraction and encapsulation are constantly conflated. What is the difference?
Answer
Abstraction is a design-time act: deciding which concepts exist and what their contract is — you name IPremiumCalculator and declare that it turns a risk profile into an amount. Encapsulation is an implementation-time act: hiding how a specific type fulfils its contract. Abstraction removes detail from the model; encapsulation hides detail from the caller. You can have one without the other: a public field on an interface-driven type is abstraction without encapsulation; a class with private fields and a 40-method surface that mirrors its database row is encapsulation without abstraction.
Example — Insurance
Abstraction is the contract; encapsulation is what each implementation keeps to itself.
// Abstraction: the concept, stated as a contract.
public interface IPremiumCalculator
{
decimal Calculate(RiskProfile risk);
}
// Encapsulation: the rating tables and load factors are nobody's business.
public sealed class MotorPremiumCalculator : IPremiumCalculator
{
private readonly IReadOnlyDictionary<string, decimal> _zoneLoading;
private const decimal BaseRate = 0.0325m;
public decimal Calculate(RiskProfile risk) =>
BaseRate * risk.VehicleValue * _zoneLoading[risk.RegistrationZone] * NoClaimFactor(risk);
private static decimal NoClaimFactor(RiskProfile risk) =>
risk.ClaimFreeYears >= 5 ? 0.75m : 1.0m;
}
Example — Employee
public interface ITaxWithholding // abstraction
{
decimal Withhold(decimal gross, TaxYear year);
}
public sealed class ProgressiveTaxWithholding : ITaxWithholding
{
private readonly Band[] _bands; // encapsulation
public decimal Withhold(decimal gross, TaxYear year) => /* band walk */ 0m;
}
Payroll depends on ITaxWithholding. When the finance act changes the bands, payroll does not recompile.
Example — Student
public interface IGradingScheme { Grade Grade(decimal percentage); }
public sealed class CurvedGradingScheme : IGradingScheme
{
private readonly decimal _cohortMean, _cohortStdDev; // hidden entirely
public Grade Grade(decimal percentage) => /* z-score mapping */ Grade.B;
}
5. Inheritance — and why is the standard advice "prefer composition"?
Answer
Inheritance couples a subclass to its base class's implementation, not just its contract: protected state, construction order, and every future change the base author makes. That coupling is the strongest in the language and cannot be varied at runtime. Composition swaps that for a field and a delegation call — weaker coupling, runtime-swappable, and it does not consume C#'s single base-class slot. Inheritance earns its place when the relationship is genuinely permanent and substitutable, and when the base class was designed for extension.
Example — Insurance
Inheritance used well — the hierarchy is stable, and the base class defines an explicit extension point:
public abstract class Policy
{
public string PolicyNumber { get; }
public decimal Premium { get; protected set; }
protected Policy(string policyNumber) => PolicyNumber = policyNumber;
public abstract RenewalTerms GetRenewalTerms(); // designed extension point
}
public sealed class MotorPolicy : Policy
{
public int NoClaimYears { get; }
public override RenewalTerms GetRenewalTerms() =>
new(Premium * (NoClaimYears >= 5 ? 0.85m : 1.0m), DateOnly.FromDateTime(DateTime.UtcNow).AddYears(1));
}
Composition for the part that varies independently — discounting is not "a kind of policy":
public sealed class Policy
{
private readonly IDiscountRule _discount; // swappable per policy, at runtime
public Policy(IDiscountRule discount) => _discount = discount;
public decimal NetPremium() => _discount.Apply(Premium);
}
Example — Employee
The classic bad hierarchy: Manager : Employee looks right until someone is promoted, and you cannot change an object's type at runtime.
// Fragile — promotion requires constructing a new object and fixing every reference.
public class Manager : Employee { public List<Employee> Reports { get; } = new(); }
// Composed — a role is state, and state changes.
public sealed class Employee
{
private readonly List<Role> _roles = new();
public bool CanApprove(LeaveRequest r) => _roles.Any(role => role.Grants(Permission.ApproveLeave));
public void Assign(Role role) => _roles.Add(role);
}
Example — Student
PartTimeStudent : Student breaks the same way — enrolment status changes every semester.
public sealed class Student
{
public EnrolmentMode Mode { get; private set; } // FullTime | PartTime | OnLeave
private IFeeSchedule Fees => Mode switch
{
EnrolmentMode.FullTime => new FullTimeFees(),
EnrolmentMode.PartTime => new PerCreditFees(),
_ => new NoFees()
};
public void SwitchTo(EnrolmentMode mode) => Mode = mode; // impossible with subclassing
}
6. Polymorphism — distinguish the kinds and how each dispatches
Answer
C# has three. Ad-hoc polymorphism (overloading) is resolved by the compiler from the static types of the arguments — zero runtime cost, and it is not extensible. Subtype polymorphism (virtual/override, interfaces) is resolved by the runtime from the object's method table — one indirect call, and it is the extensible one. Parametric polymorphism (generics) is resolved by the runtime type system: reference-type instantiations share one JIT-compiled body, value-type instantiations each get their own specialised, non-boxing body.
Example — Insurance
Subtype polymorphism: the claims engine never learns the concrete policy types.
public abstract class Policy { public abstract decimal Excess(Claim claim); }
public sealed class MotorPolicy : Policy { public override decimal Excess(Claim c) => 500m; }
public sealed class HealthPolicy : Policy { public override decimal Excess(Claim c) => c.Amount * 0.10m; }
decimal Payable(Policy policy, Claim claim) =>
Math.Max(0, claim.Amount - policy.Excess(claim)); // one call site, all current and future policies
Example — Employee
Ad-hoc vs subtype in the same class — note that overload choice is fixed at compile time:
public sealed class PayrollService
{
public void Pay(Employee e) => Console.WriteLine("Employee run");
public void Pay(Contractor c) => Console.WriteLine("Contractor run");
}
Person p = new Contractor();
service.Pay(p); // does not compile — overloads look at the *static* type, not the object
Example — Student
Parametric polymorphism, with a constraint so the code stays type-safe:
public sealed class Repository<T> where T : IEntity
{
private readonly Dictionary<Guid, T> _store = new();
public T? Find(Guid id) => _store.TryGetValue(id, out var e) ? e : default;
}
var students = new Repository<Student>();
var courses = new Repository<Course>(); // no casting, no boxing, one source
7. Composition, aggregation, association — and does the distinction matter in code?
Answer
All three are "has-a"; they differ in lifetime ownership. Composition: the part cannot exist without the whole and dies with it — a Coverage outside its Policy is meaningless. Aggregation: the whole references a part that has its own independent lifetime — a Department groups Employees that outlive it. Association: a plain reference with no ownership at all. It matters concretely in three places: cascade-delete configuration, aggregate boundaries in DDD, and whether the part gets its own repository.
Example — Insurance
public sealed class Policy // composition
{
private readonly List<Coverage> _coverages = new(); // created here, deleted with the policy
public Coverage AddCoverage(string peril, decimal limit)
{
var c = new Coverage(peril, limit);
_coverages.Add(c);
return c;
}
}
public sealed class Claim // association
{
public string PolicyNumber { get; } // references, does not own
}
EF Core mirrors this: Coverage is an owned type / cascade-delete child, Claim holds a plain FK.
Example — Employee
public sealed class Department // aggregation
{
private readonly List<Employee> _members = new(); // employees survive the department
public void Transfer(Employee e) => _members.Add(e);
}
public sealed class Employee
{
private readonly List<Timesheet> _timesheets = new(); // composition — meaningless without the employee
}
Delete a department and employees are reassigned, not deleted. Delete an employee and the timesheets go too.
Example — Student
public sealed class Course // aggregation: students exist independently
{
private readonly List<Enrolment> _enrolments = new();
}
public sealed class Student
{
private readonly List<Enrolment> _enrolments = new(); // the join entity is owned by neither, really
}
Enrolment carrying its own data (grade, enrolment date) is the sign it is a first-class entity, not a composition detail.
Types and contracts
8. Abstract class vs interface — how do you actually choose in 2024?
Answer
Default to an interface: it is a pure contract, a type can implement many, and it does not spend the single base-class slot. Reach for an abstract class when you need to share state (protected fields), enforce a construction invariant through a protected constructor, or provide a template method whose skeleton must not be overridden. C# 8's default interface members blurred the line for behaviour but not for state — interfaces still cannot hold instance fields, so anything requiring per-instance data still needs a class.
Example — Insurance
Abstract class where shared state and a construction invariant exist:
public abstract class Policy
{
public string PolicyNumber { get; }
protected decimal BasePremium { get; } // shared state — an interface cannot do this
protected Policy(string policyNumber, decimal basePremium)
{
if (basePremium <= 0) throw new ArgumentOutOfRangeException(nameof(basePremium));
PolicyNumber = policyNumber; // no subclass can skip this
BasePremium = basePremium;
}
public decimal Premium() => BasePremium * RiskMultiplier(); // template method
protected abstract decimal RiskMultiplier(); // the only variable step
}
Interfaces for capabilities that cut across the hierarchy:
public interface IRenewable { RenewalTerms GetRenewalTerms(); }
public interface ICancellable { Refund Cancel(DateOnly on); }
public sealed class MotorPolicy : Policy, IRenewable, ICancellable { /* … */ }
Example — Employee
public abstract class Worker
{
protected Worker(string id) => Id = id;
public string Id { get; }
public abstract decimal GrossPay(Period period);
}
public interface IApprover { bool CanApprove(LeaveRequest request); }
// A Contractor is a Worker but not an Approver; a Manager is both.
public sealed class Contractor : Worker { public override decimal GrossPay(Period p) => /* … */ 0m; }
Example — Student
public interface IGradable { Grade Grade(); }
public interface IAuditable { DateTime LastModifiedUtc { get; } }
// One class, several orthogonal contracts — impossible with single inheritance.
public sealed class Assignment : IGradable, IAuditable { /* … */ }
9. Do C# 8 default interface implementations make abstract classes obsolete?
Answer
No. They solve exactly one problem: adding a member to a published interface without breaking existing implementers. They do not give interfaces instance state, constructors, or destructor semantics, and their dispatch rules are surprising — a default implementation is only callable through the interface reference, not through the concrete type. Treat them as a versioning tool, not a design tool.
Example — Insurance
public interface IPremiumCalculator
{
decimal Calculate(RiskProfile risk);
// Added in v2. Existing implementers keep compiling.
decimal CalculateWithLoading(RiskProfile risk, decimal loading) =>
Calculate(risk) * (1 + loading);
}
public sealed class MotorPremiumCalculator : IPremiumCalculator
{
public decimal Calculate(RiskProfile risk) => 1000m;
}
var calc = new MotorPremiumCalculator();
// calc.CalculateWithLoading(risk, 0.1m); // does NOT compile
((IPremiumCalculator)calc).CalculateWithLoading(risk, 0.1m); // works — 1100
Example — Employee
public interface IPayrollExporter
{
Stream Export(PayrollRun run);
string FileName(PayrollRun run) => $"payroll-{run.Period:yyyyMM}.csv"; // sensible default
}
Every existing exporter inherits the naming convention; a bank-specific exporter overrides it.
Example — Student
public interface ITranscriptFormatter
{
string Format(Transcript t);
string ContentType => "text/plain"; // one line instead of a new base class
}
10. What is explicit interface implementation and when is it the right call?
Answer
Declaring a member as decimal IPremiumCalculator.Calculate(...) implements the interface without adding the member to the class's public surface — it is reachable only through an interface-typed reference. Three legitimate uses: resolving a signature collision when two interfaces demand the same signature with different semantics; keeping a legacy or infrastructure contract (IDisposable, ISerializable, IComparable) out of the domain-facing API; and deliberately discouraging a call that is only correct in a specific context.
Example — Insurance
Two contracts, same signature, different meanings:
public interface IUnderwritingRule { bool Evaluate(Policy p); } // "is this risk acceptable?"
public interface IComplianceRule { bool Evaluate(Policy p); } // "does this breach regulation?"
public sealed class HighValueMotorRule : IUnderwritingRule, IComplianceRule
{
bool IUnderwritingRule.Evaluate(Policy p) => p.SumInsured <= 250_000m;
bool IComplianceRule.Evaluate(Policy p) => p.Holder.SanctionsChecked;
}
IComplianceRule rule = new HighValueMotorRule();
rule.Evaluate(policy); // unambiguous — the reference type picks the implementation
Example — Employee
Hiding infrastructure noise from the domain surface:
public sealed class Employee : IComparable<Employee>
{
public string Id { get; init; } = "";
public decimal Salary { get; private set; }
// Sorting is an infrastructure concern; it should not clutter IntelliSense on Employee.
int IComparable<Employee>.CompareTo(Employee? other) =>
string.CompareOrdinal(Id, other?.Id);
}
Example — Student
Discouraging a mutation that is only valid during import:
public sealed class Transcript : IBulkLoadable
{
void IBulkLoadable.LoadRaw(IEnumerable<Grade> grades) => _grades.AddRange(grades);
// Ordinary code sees only RecordGrade(); the importer casts to IBulkLoadable.
}
11. C# has no multiple class inheritance. How do you get the same effect, and what is the diamond problem?
Answer
The diamond problem: if D inherits from both B and C, which themselves inherit from A, and both override A.M(), the runtime cannot decide which M D inherits — and D may end up with two copies of A's state. C# sidesteps it by allowing exactly one base class while permitting many interfaces (which carry no state, so there is nothing to duplicate). You compose the missing behaviour: implement several interfaces and delegate to injected collaborators, or use extension methods for stateless helpers.
Example — Insurance
public interface IRenewable { RenewalTerms Renew(); }
public interface IReinsurable { decimal CededShare(); }
public sealed class MotorPolicy : Policy, IRenewable, IReinsurable
{
private readonly IRenewalEngine _renewal; // behaviour composed in
private readonly IReinsuranceTreaty _treaty;
public RenewalTerms Renew() => _renewal.ComputeFor(this);
public decimal CededShare() => _treaty.ShareOf(this);
}
Example — Employee
C# 8 default members can create an ambiguity, and the compiler forces you to resolve it:
public interface IPayable { decimal Net(decimal gross) => gross * 0.80m; }
public interface ITaxable { decimal Net(decimal gross) => gross * 0.70m; }
public sealed class Contractor : IPayable, ITaxable
{
// Required: without this, calling Net through a Contractor-typed reference is ambiguous.
public decimal Net(decimal gross) => gross * 0.75m;
}
Example — Student
public interface IEnrollable { void Enrol(Course c); }
public interface IBillable { Invoice RaiseInvoice(); }
public sealed class Student : Person, IEnrollable, IBillable { /* delegate to services */ }
12. sealed, static, partial, nested — what are each actually for?
Answer
sealed blocks further inheritance (on a class) or blocks further overriding (on an override method); it is a design statement and a JIT devirtualisation hint. static classes cannot be instantiated or inherited and hold only static members — correct for genuinely stateless helpers, and a testability hazard when they hold state or reach out to I/O. partial splits one type across files, which exists for generated code — hand-written partial classes are usually a class that should have been two. Nested types express a helper that only makes sense inside its parent, and a private nested type can be an implementation detail nobody else can name.
Example — Insurance
public sealed class MotorPolicy : Policy { } // no further specialisation intended
public static class PremiumRounding // stateless, no I/O — a fine static class
{
public static decimal ToBillable(decimal premium) => Math.Round(premium, 2, MidpointRounding.AwayFromZero);
}
public sealed class ClaimAssessment
{
private sealed record Deduction(string Reason, decimal Amount); // nested, private, invisible outside
private readonly List<Deduction> _deductions = new();
}
Example — Employee
partial in its proper habitat — generated plus hand-written halves of the same type:
// Employee.g.cs — generated from the HR schema, regenerated on every build.
public partial class Employee { public string Id { get; set; } = ""; }
// Employee.cs — hand-written, survives regeneration.
public partial class Employee
{
public bool IsProbationComplete => HireDateUtc.AddMonths(6) <= DateTime.UtcNow;
}
Example — Student
The static-class trap. This is untestable, because no test can substitute the clock:
public static class EnrolmentWindow
{
public static bool IsOpen() => DateTime.UtcNow.Month is 7 or 8; // hidden dependency on the clock
}
// Better: an instance with an injected clock.
public sealed class EnrolmentWindow(TimeProvider clock)
{
public bool IsOpen() => clock.GetUtcNow().Month is 7 or 8;
}
Polymorphism mechanics
13. virtual, override, abstract, new — what does each mean, and how do they dispatch?
Answer
virtual declares a member with a default body that subclasses may replace. abstract declares one with no body that subclasses must replace, and forces the class to be abstract. override replaces an inherited virtual/abstract member and participates in runtime dispatch — the object's actual type decides. new does not override anything; it introduces a separate member that hides the base one, and dispatch is decided at compile time by the reference's static type. That last distinction is the whole question.
Example — Insurance
public class Policy
{
public virtual decimal Excess() => 250m;
public virtual string Describe() => "Standard policy";
}
public sealed class MotorPolicy : Policy
{
public override decimal Excess() => 500m; // overrides — runtime dispatch
public new string Describe() => "Motor policy"; // hides — compile-time dispatch
}
Policy p = new MotorPolicy();
Console.WriteLine(p.Excess()); // 500 — override wins, actual type decides
Console.WriteLine(p.Describe()); // "Standard policy" — reference is Policy, so the base member is chosen
MotorPolicy m = new MotorPolicy();
Console.WriteLine(m.Describe()); // "Motor policy" — same object, different answer
Two references to one object returning different strings is the bug new creates.
Example — Employee
abstract when there is no sensible default:
public abstract class Worker
{
public abstract decimal GrossPay(Period p); // no default is meaningful
public virtual decimal Bonus(Period p) => 0m; // a default that is often right
}
public sealed class SalariedEmployee : Worker
{
public override decimal GrossPay(Period p) => AnnualSalary / 12;
// Bonus not overridden — inherits 0m.
}
Example — Student
public abstract class Assessment
{
public abstract decimal Score();
public virtual bool IsPass() => Score() >= 40m; // overridable policy
}
public sealed class Dissertation : Assessment
{
public override decimal Score() => /* … */ 0m;
public override bool IsPass() => Score() >= 50m; // higher bar
}
14. Explain constructor execution order with inheritance, and why calling a virtual method from a constructor is dangerous
Answer
For new Derived(), C# runs: derived field initialisers → base field initialisers → base constructor body → derived constructor body. (This differs from Java and C++, where the base constructor runs before derived field initialisers.) The danger follows directly: a virtual call inside the base constructor dispatches to the derived override, which executes before the derived constructor body has run. Fields assigned in that body — including readonly ones — are still at their defaults.
Example — Insurance
public abstract class Policy
{
protected Policy() => Console.WriteLine($"Base ctor sees excess = {Excess()}");
public abstract decimal Excess();
}
public sealed class MotorPolicy : Policy
{
private readonly decimal _agreedExcess;
public MotorPolicy(decimal agreedExcess)
{
_agreedExcess = agreedExcess; // runs AFTER the base ctor
}
public override decimal Excess() => _agreedExcess;
}
var p = new MotorPolicy(750m);
// Prints: Base ctor sees excess = 0 <-- not 750
The fix is to not call virtuals from constructors — pass the value to the base constructor, or use a factory method that constructs then initialises.
Example — Employee
Order made visible:
static string Trace(string stage) { Console.WriteLine(stage); return stage; }
public class Worker
{
private readonly string _a = Trace("2. base field initialiser");
public Worker() => Trace("3. base ctor body");
}
public sealed class Manager : Worker
{
private readonly string _b = Trace("1. derived field initialiser");
public Manager() => Trace("4. derived ctor body");
}
_ = new Manager();
// 1. derived field initialiser
// 2. base field initialiser
// 3. base ctor body
// 4. derived ctor body
Derived field initialisers running before the base constructor is the part that differs from Java and C++.
Example — Student
Constructor chaining with this(...) to keep the invariant in exactly one place:
public sealed class Student
{
public string Id { get; }
public EnrolmentMode Mode { get; }
public Student(string id) : this(id, EnrolmentMode.FullTime) { }
public Student(string id, EnrolmentMode mode) // the single real constructor
{
if (string.IsNullOrWhiteSpace(id)) throw new ArgumentException(nameof(id));
Id = id;
Mode = mode;
}
}
15. Method overloading: what are the resolution rules, and where does it bite?
Answer
Overload resolution picks the best applicable member using only the static types of the arguments, at compile time. Rules in order: exact match beats implicit conversion; a more derived parameter type beats a less derived one; non-optional beats optional; non-params beats params; and a non-generic method beats a generic one that would require inference. It bites in three predictable places: null arguments (ambiguous between reference types), integer literals silently choosing int over decimal, and adding an overload to a shipped library silently rebinding callers on recompile.
Example — Insurance
The money overload trap. int converts implicitly to both double and decimal, and neither conversion is "better" than the other, so this does not compile:
public void RecordPayment(decimal amount) { }
public void RecordPayment(double amount) { }
RecordPayment(1000); // CS0121: ambiguous between the decimal and double overloads
RecordPayment(1000m); // fine — the literal picks decimal
A compile error is the good outcome. The dangerous version is when only one overload exists and it is the wrong type:
public void RecordPayment(double amount) { } // only overload
RecordPayment(1000); // compiles silently — money is now in binary floating point
Money overloads should not sit next to double at all.
Example — Employee
null ambiguity, and the fix:
public void Notify(Employee e) { }
public void Notify(Contractor c) { }
Notify(null); // CS0121: ambiguous
Notify((Employee?)null); // explicit — resolves
Example — Student
Derived-type preference, which surprises people when a base-typed variable is passed:
public void Register(Person p) => Console.WriteLine("Person");
public void Register(Student s) => Console.WriteLine("Student");
Student s = new();
Person p = s;
Register(s); // "Student" — static type is Student
Register(p); // "Person" — same object, static type is Person
16. Explain covariance and contravariance with a case where getting it wrong causes a runtime failure
Answer
Covariance (out) lets a generic type be used with a more derived argument where a less derived one is expected — safe when T only appears in output positions. Contravariance (in) is the reverse — safe when T only appears in input positions. C# enforces this on generic interfaces and delegates only, and only for reference types. Arrays are the hole: C# arrays are covariant but not type-safe, so Policy[] a = new MotorPolicy[1]; a[0] = new HealthPolicy(); compiles and throws ArrayTypeMismatchException at runtime.
Example — Insurance
The array hole, and the type-safe alternative:
Policy[] policies = new MotorPolicy[2]; // legal — arrays are covariant
policies[0] = new HealthPolicy(); // compiles, throws ArrayTypeMismatchException at runtime
IEnumerable<Policy> safe = new List<MotorPolicy>(); // IEnumerable<out T> — covariant and safe
// safe has no Add, so there is no way to insert a HealthPolicy.
IEnumerable<out T> is safe precisely because T never appears as an input.
Example — Employee
Contravariance — a comparer for the general type works wherever a specific one is needed:
public sealed class ByIdComparer : IComparer<Person>
{
public int Compare(Person? a, Person? b) => string.CompareOrdinal(a?.Id, b?.Id);
}
// IComparer<in T>: an IComparer<Person> is acceptable as an IComparer<Employee>.
var employees = new List<Employee>();
employees.Sort(new ByIdComparer());
Example — Student
Writing your own variant interface:
public interface IReader<out T> { T Read(Guid id); } // T only in output
public interface IWriter<in T> { void Write(T item); } // T only in input
IReader<Person> reader = new StudentReader(); // covariant: IReader<Student> → IReader<Person>
IWriter<Student> writer = new PersonWriter(); // contravariant: IWriter<Person> → IWriter<Student>
State and identity
17. Value types vs reference types — where does each live, and when does the distinction actually matter?
Answer
A reference type variable holds a pointer to a heap object; assignment copies the pointer, so both names see the same object. A value type variable holds the data inline — in a register, on the stack, or embedded in its containing object — and assignment copies the whole thing. "Structs live on the stack" is a common but wrong shorthand: a struct field inside a class lives on the heap, inside that class's object. It matters for aliasing semantics, allocation pressure, and equality defaults.
Example — Insurance
Copy semantics changing behaviour:
public struct Money { public decimal Amount; }
public sealed class Premium { public decimal Amount; }
var m1 = new Money { Amount = 100 };
var m2 = m1; m2.Amount = 500;
Console.WriteLine(m1.Amount); // 100 — independent copy
var p1 = new Premium { Amount = 100 };
var p2 = p1; p2.Amount = 500;
Console.WriteLine(p1.Amount); // 500 — same object
Mutable structs are the reason readonly struct exists — make Money a readonly record struct and the confusion disappears.
Example — Employee
Allocation pressure in a payroll run over a million rows:
public readonly record struct PayLine(int EmployeeId, decimal Gross, decimal Net);
var lines = new List<PayLine>(1_000_000); // one contiguous buffer, zero per-item allocations
// The class version would be 1,000,000 heap objects + 1,000,000 pointers = far more GC work.
Example — Student
The mutable-struct gotcha, which still catches experienced developers:
struct Counter { public int Value; public void Increment() => Value++; }
var list = new List<Counter> { new() };
list[0].Increment(); // compiles, and silently does NOTHING —
// the indexer returns a copy, which is mutated then discarded
Console.WriteLine(list[0].Value); // 0
// list[0].Value = 1; // CS1612: cannot modify the return value of an indexer
var arr = new Counter[1];
arr[0].Increment(); // this DOES mutate — array indexing yields a variable, not a copy
Console.WriteLine(arr[0].Value); // 1
Two collections, the same struct, opposite behaviour. This is the argument for readonly struct.
18. What is boxing, when does it happen invisibly, and why does it matter?
Answer
Boxing allocates a heap object, copies a value type into it, and hands back a reference — it happens whenever a value type is converted to object, to dynamic, or to an interface it implements. Unboxing is the reverse and requires an exact type match. The cost is an allocation plus a copy plus later GC work, and the danger is that it is invisible at the call site: string.Format, non-generic collections, IComparable on a struct, and Enum.HasFlag before .NET Core 2.1 all boxed silently.
Example — Insurance
decimal premium = 1250.75m;
object boxed = premium; // box: allocation + copy
decimal back = (decimal)boxed; // unbox: exact type required
// int wrong = (int)boxed; // InvalidCastException — no widening on unbox
Example — Employee
The invisible one, in a hot payroll loop:
// Boxes the int and the decimal on every iteration.
foreach (var e in employees)
logger.LogDebug("Employee {Id} net {Net}", e.Id, e.Net); // params object?[]
// No boxing — the generic overloads take the values directly.
foreach (var e in employees)
logger.LogDebug($"Employee {e.Id} net {e.Net}"); // interpolated string handler, .NET 6+
.NET 6's interpolated string handlers exist precisely to remove this boxing.
Example — Student
Comparing structs through an interface boxes both operands:
public readonly struct Score : IComparable<Score>
{
public int Value { get; init; }
public int CompareTo(Score other) => Value.CompareTo(other.Value); // generic — no boxing
}
// This constraint keeps List<Score>.Sort() boxing-free:
public static void SortAll<T>(List<T> items) where T : IComparable<T> => items.Sort();
// Without the constraint, T would be compared via the non-generic IComparable and box every call.
19. What is the Equals/GetHashCode contract, and what breaks when you violate it?
Answer
Three rules: equal objects must return the same hash code; the hash code of an object must not change while it is in a hash-based collection; and Equals must be reflexive, symmetric, transitive and consistent. The classic violation is overriding Equals and forgetting GetHashCode — the object then compares equal but lands in a different bucket, so Dictionary and HashSet silently lose it. The subtler and more dangerous violation is hashing on a mutable field.
Example — Insurance
The mutable-key bug, which loses data with no exception:
public sealed class Policy
{
public string PolicyNumber { get; set; } = ""; // mutable — and used in the hash
public override bool Equals(object? o) => o is Policy p && p.PolicyNumber == PolicyNumber;
public override int GetHashCode() => PolicyNumber.GetHashCode();
}
var set = new HashSet<Policy>();
var policy = new Policy { PolicyNumber = "MTR-001" };
set.Add(policy);
policy.PolicyNumber = "MTR-002"; // hash changes while inside the set
Console.WriteLine(set.Contains(policy)); // False — it is in the wrong bucket
Console.WriteLine(set.Count); // 1 — the object is there, and unreachable
The fix is to hash only on immutable state — make PolicyNumber init-only.
Example — Employee
Correct implementation with HashCode.Combine:
public sealed class Employee : IEquatable<Employee>
{
public string Id { get; init; } = ""; // immutable identity
public string Name { get; set; } = ""; // mutable, deliberately NOT part of identity
public bool Equals(Employee? other) => other is not null && other.Id == Id;
public override bool Equals(object? o) => Equals(o as Employee);
public override int GetHashCode() => HashCode.Combine(Id);
}
Implementing IEquatable<T> matters: generic collections check for it and avoid boxing/casting.
Example — Student
Records do all of this for you, correctly:
public sealed record CourseCode(string Faculty, int Number);
var a = new CourseCode("CS", 301);
var b = new CourseCode("CS", 301);
Console.WriteLine(a == b); // True — synthesised value equality
Console.WriteLine(a.GetHashCode() == b.GetHashCode()); // True — synthesised, consistent
20. How do you design a genuinely immutable class, and why bother?
Answer
Immutable means no observable state change after construction: readonly or init-only members, no mutating methods (operations return a new instance), defensive copies of any mutable input, and a sealed class so a subclass cannot add mutable state. The payoff is that the object is inherently thread-safe, can be cached and shared freely, is safe as a dictionary key, and cannot be corrupted by a caller you did not anticipate.
Example — Insurance
public sealed class Money : IEquatable<Money>
{
public decimal Amount { get; }
public string Currency { get; }
public Money(decimal amount, string currency)
{
if (string.IsNullOrWhiteSpace(currency)) throw new ArgumentException(nameof(currency));
Amount = amount;
Currency = currency;
}
public Money Add(Money other)
{
if (other.Currency != Currency)
throw new InvalidOperationException("Cannot add different currencies.");
return new Money(Amount + other.Amount, Currency); // new instance, never mutation
}
public bool Equals(Money? o) => o is not null && o.Amount == Amount && o.Currency == Currency;
public override int GetHashCode() => HashCode.Combine(Amount, Currency);
}
Example — Employee
The defensive-copy requirement — a readonly field holding a List<T> is not immutable:
public sealed class PayrollSnapshot
{
private readonly PayLine[] _lines; // copied on the way in
public PayrollSnapshot(IEnumerable<PayLine> lines) => _lines = lines.ToArray();
public IReadOnlyList<PayLine> Lines => _lines; // and never handed out as a mutable array
public decimal Total => _lines.Sum(l => l.Net);
}
Without .ToArray(), the caller keeps a reference to the original list and can mutate the "snapshot" afterwards.
Example — Student
Records with init give you the same thing with far less ceremony:
public sealed record Enrolment(Guid StudentId, Guid CourseId, DateOnly EnrolledOn)
{
public Grade? Grade { get; init; }
// "Mutation" produces a new instance.
public Enrolment WithGrade(Grade grade) => this with { Grade = grade };
}
21. Shallow copy vs deep copy — how do you implement each, and which does record give you?
Answer
A shallow copy duplicates the top-level object and copies references, so both copies share the same nested objects. A deep copy duplicates the whole reachable graph. MemberwiseClone() is shallow; record's with expression and its synthesised copy constructor are also shallow. Deep copying requires explicit recursion (or serialisation round-tripping, which is slow and drags in serialiser constraints).
Example — Insurance
public sealed class Policy
{
public string Number { get; set; } = "";
public List<Coverage> Coverages { get; set; } = new();
public Policy ShallowCopy() => (Policy)MemberwiseClone();
public Policy DeepCopy() => new()
{
Number = Number,
Coverages = Coverages.Select(c => c with { }).ToList() // new list AND new items
};
}
var original = new Policy { Number = "MTR-001", Coverages = { new Coverage("Fire", 10_000m) } };
var shallow = original.ShallowCopy();
shallow.Coverages.Add(new Coverage("Theft", 5_000m));
Console.WriteLine(original.Coverages.Count); // 2 — the "copy" mutated the original
Example — Employee
The with expression's shallowness, demonstrated:
public record PayrollRun(string Period)
{
public List<PayslipLine> Lines { get; init; } = new();
}
var april = new PayrollRun("2024-04") { Lines = { new PayslipLine("E-1", 5000m) } };
var may = april with { Period = "2024-05" };
may.Lines.Add(new PayslipLine("E-2", 6000m));
Console.WriteLine(april.Lines.Count); // 2 — `with` copied the reference, not the list
Fix by making the collection immutable: public ImmutableArray<PayslipLine> Lines { get; init; }.
Example — Student
public sealed record Transcript(Guid StudentId, ImmutableArray<Grade> Grades)
{
// With ImmutableArray, `with` is effectively a deep copy — nothing downstream is mutable.
public Transcript Add(Grade g) => this with { Grades = Grades.Add(g) };
}
Design principles
22. Walk through SOLID with a real violation and fix for each
Answer
Single responsibility — one reason to change. Open/closed — extend without editing. Liskov substitution — a subtype must honour its base type's contract. Interface segregation — no client should depend on methods it does not use. Dependency inversion — depend on abstractions, and the abstraction belongs to the consumer, not the provider. The last clause is the one most people miss and the one that makes DIP more than "use interfaces".
Example — Insurance
SRP: this class changes when pricing rules change, when the schema changes, and when the email template changes.
// Violation
public class PolicyService
{
public decimal CalculatePremium(Policy p) { /* rating */ return 0m; }
public void Save(Policy p) { /* SQL */ }
public void EmailConfirmation(Policy p) { /* SMTP */ }
}
// Fixed — three reasons to change, three types.
public sealed class PremiumCalculator { public decimal Calculate(Policy p) => 0m; }
public sealed class PolicyRepository { public Task SaveAsync(Policy p) => Task.CompletedTask; }
public sealed class PolicyNotifier { public Task ConfirmAsync(Policy p) => Task.CompletedTask; }
OCP: a switch that grows with every new product versus a strategy set that does not.
// Violation — every new product edits this method.
decimal Premium(Policy p) => p.Type switch
{
"Motor" => p.Value * 0.03m,
"Health" => p.Value * 0.05m,
_ => throw new NotSupportedException()
};
// Fixed — a new product is a new class plus a DI registration.
public interface IRatingStrategy { string Product { get; } decimal Rate(Policy p); }
public sealed class PremiumCalculator(IEnumerable<IRatingStrategy> strategies)
{
private readonly Dictionary<string, IRatingStrategy> _byProduct =
strategies.ToDictionary(s => s.Product);
public decimal Rate(Policy p) => _byProduct[p.Type].Rate(p);
}
Example — Employee
LSP violated — Contractor cannot honour the base contract, and the throw proves it:
// Violation
public class Employee { public virtual LeaveBalance Leave() => new(25); }
public class Contractor : Employee
{
public override LeaveBalance Leave() => throw new NotSupportedException(); // not substitutable
}
// Fixed — split the capability out of the hierarchy.
public abstract class Worker { public abstract decimal GrossPay(Period p); }
public interface ITakesLeave { LeaveBalance Leave(); }
public sealed class Employee : Worker, ITakesLeave { /* … */ }
public sealed class Contractor : Worker { /* no leave, and nothing lies about it */ }
ISP — a payroll exporter forced to implement importing it never does:
// Violation
public interface IPayrollGateway { Stream Export(PayrollRun r); PayrollRun Import(Stream s); }
// Fixed
public interface IPayrollExporter { Stream Export(PayrollRun r); }
public interface IPayrollImporter { PayrollRun Import(Stream s); }
Example — Student
DIP — note that IGradeStore is defined in the domain project, and the EF implementation in infrastructure depends inward:
// Domain layer — owns the abstraction it needs.
public interface IGradeStore { Task<Transcript> LoadAsync(Guid studentId, CancellationToken ct); }
public sealed class GradingService(IGradeStore store) // depends on the abstraction
{
public async Task<decimal> GpaAsync(Guid id, CancellationToken ct) =>
(await store.LoadAsync(id, ct)).Gpa();
}
// Infrastructure layer — depends on the domain, not the other way round.
public sealed class EfGradeStore(SchoolDbContext db) : IGradeStore { /* … */ }
23. Dependency injection: constructor, property or method — and what do the lifetimes really mean?
Answer
Constructor injection for required collaborators — the object cannot be constructed in an invalid state, and the constructor signature honestly documents the dependencies. Property injection only for genuinely optional dependencies with a safe default (a logger). Method injection when the dependency varies per call, not per object. Lifetimes: transient = a new instance per resolution; scoped = one per request/scope; singleton = one per container. The bug that costs production outages is the captive dependency — a singleton capturing a scoped dependency, which keeps a DbContext alive for the life of the process.
Example — Insurance
public sealed class PolicyIssuanceService(
IPolicyRepository repository, // required — constructor
IPremiumCalculator calculator,
ILogger<PolicyIssuanceService> logger)
{
public async Task<Policy> IssueAsync(Application app, IClock clock, CancellationToken ct)
{
// clock varies per call in back-dated issuance — method injection is right here
var policy = Policy.Issue(app, calculator.Calculate(app.Risk), clock.UtcNow);
await repository.AddAsync(policy, ct);
return policy;
}
}
Example — Employee
The captive dependency, and how it manifests:
// PayrollCache is a singleton; PayrollDbContext is scoped.
builder.Services.AddSingleton<PayrollCache>();
builder.Services.AddDbContext<PayrollDbContext>(); // scoped by default
public sealed class PayrollCache(PayrollDbContext db) // BUG: captures the first request's context
{
// The DbContext is now a process-lifetime object: stale data, unbounded change tracker,
// and "A second operation was started on this context" under concurrency.
}
// Fix: resolve the scoped dependency per use.
public sealed class PayrollCache(IServiceScopeFactory scopeFactory)
{
public async Task<decimal> TotalAsync(string period, CancellationToken ct)
{
using var scope = scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<PayrollDbContext>();
return await db.PayLines.Where(l => l.Period == period).SumAsync(l => l.Net, ct);
}
}
builder.Services validates this at startup when ValidateScopes is on — which is the default in Development only. Turn it on in all environments.
Example — Student
Registering a strategy set, and resolving by key (.NET 8):
builder.Services.AddKeyedScoped<IGradingScheme, CurvedGradingScheme>("curved");
builder.Services.AddKeyedScoped<IGradingScheme, AbsoluteGradingScheme>("absolute");
public sealed class ResultsService([FromKeyedServices("curved")] IGradingScheme scheme)
{
public Grade Grade(decimal percentage) => scheme.Grade(percentage);
}
24. What is an anemic domain model, and when is it actually acceptable?
Answer
An anemic model is a set of property bags with no behaviour, where all the rules live in "service" classes — structurally procedural code wearing OO clothing. The cost is exactly the cost of losing OOP's main benefit: the invariants have no home, so every service that touches Policy must independently remember the rules. It is acceptable, and often correct, when the type genuinely has no invariants: DTOs, view models, integration contracts, and thin CRUD services over a schema with no domain logic.
Example — Insurance
// Anemic — the rule "cannot cancel a claimed policy" is nowhere, so every service re-implements it.
public class Policy { public PolicyStatus Status { get; set; } public bool HasOpenClaim { get; set; } }
public class CancellationService
{
public void Cancel(Policy p)
{
if (p.HasOpenClaim) throw new InvalidOperationException(); // and the same check in 4 other services
p.Status = PolicyStatus.Cancelled;
}
}
// Rich — one home for the rule, impossible to bypass.
public sealed class Policy
{
public PolicyStatus Status { get; private set; }
private readonly List<Claim> _claims = new();
public void Cancel(DateOnly on)
{
if (_claims.Any(c => c.IsOpen))
throw new InvalidOperationException("Cannot cancel while a claim is open.");
Status = PolicyStatus.Cancelled;
}
}
Example — Employee
Where anemic is right — a DTO crossing an API boundary has no invariants to protect:
public sealed record EmployeeDto(string Id, string Name, string Department, decimal Salary);
// No behaviour, and correctly so. It is a wire format, not a domain concept.
Example — Student
// Rich where rules exist…
public sealed class Enrolment
{
public void Withdraw(DateOnly on, IAcademicCalendar calendar)
{
if (on > calendar.WithdrawalDeadline(SemesterId))
throw new InvalidOperationException("Past the withdrawal deadline.");
Status = EnrolmentStatus.Withdrawn;
}
}
// …anemic where none do.
public sealed record CourseListItem(Guid Id, string Title, int Credits);
25. Law of Demeter — what is it, and is a.B.C.D always wrong?
Answer
Only talk to your immediate collaborators: a method should call methods on itself, its parameters, objects it creates, and its own fields — not on objects returned by those. policy.Holder.Address.PostCode couples the caller to three types and to the navigation path between them, so any of those three can break it. It is a heuristic, not a law: chains over data structures and fluent builders are fine, because there is no behaviour being reached through. Chains over objects with behaviour are the smell.
Example — Insurance
// Violation — the caller now knows Policy has a Holder, which has an Address, which has a PostCode.
var loading = _zoneRates[policy.Holder.Address.PostCode];
// Better — Policy answers a question about itself.
public sealed class Policy
{
private readonly Policyholder _holder;
public string RatingZone => _holder.RatingZone(); // one hop; the path is Policy's business
}
var loading = _zoneRates[policy.RatingZone];
Example — Employee
// Violation
if (employee.Department.Manager.Grade.Level >= 5) { /* … */ }
// Better — "tell, don't ask".
if (employee.RequiresSeniorApproval()) { /* … */ }
Example — Student
The acceptable chain — a fluent builder is not a Demeter violation:
var query = _db.Students
.Where(s => s.Mode == EnrolmentMode.FullTime)
.OrderBy(s => s.Surname)
.Take(50);
// Each call returns the same abstraction; there is no hidden structure being traversed.
26. DDD building blocks: entity, value object, aggregate — how do you decide which is which?
Answer
An entity has identity that persists through state change — a Policy is the same policy after repricing. A value object has no identity and is defined entirely by its attributes — Money(100, "GBP") is interchangeable with any other; it should be immutable with structural equality. An aggregate is a cluster of entities and value objects with one aggregate root as the only entry point, and it is the transactional consistency boundary — one transaction changes one aggregate; anything else is eventually consistent.
Example — Insurance
// Value object — no identity, structural equality, immutable.
public readonly record struct Money(decimal Amount, string Currency);
public sealed record CoverPeriod(DateOnly From, DateOnly To);
// Aggregate root — Coverage is only reachable through Policy.
public sealed class Policy // entity + aggregate root
{
public PolicyId Id { get; }
private readonly List<Coverage> _coverages = new(); // entities inside the boundary
public IReadOnlyList<Coverage> Coverages => _coverages;
public Money TotalPremium => new(_coverages.Sum(c => c.Premium.Amount), "GBP");
public void AddCoverage(string peril, Money premium, CoverPeriod period)
{
if (_coverages.Any(c => c.Peril == peril))
throw new InvalidOperationException("Duplicate peril.");
_coverages.Add(new Coverage(peril, premium, period)); // invariant enforced at the root
}
}
// Separate aggregate — references the policy by ID, never by navigation.
public sealed class Claim
{
public ClaimId Id { get; }
public PolicyId PolicyId { get; } // ID reference across the boundary
}
Example — Employee
public readonly record struct EmployeeId(Guid Value); // strongly-typed ID, a value object
public sealed record Address(string Line1, string City, string PostCode);
public sealed class PayrollRun // aggregate root
{
private readonly List<PayslipLine> _lines = new(); // only mutable through the root
public void AddLine(EmployeeId employee, Money gross) { /* invariant: no duplicates, not approved */ }
}
Example — Student
public readonly record struct Grade(decimal Percentage)
{
public string Letter => Percentage switch { >= 70 => "A", >= 60 => "B", >= 50 => "C", _ => "F" };
}
public sealed class Student // aggregate root
{
private readonly List<Enrolment> _enrolments = new();
public void Enrol(CourseId course, int credits) { /* credit-cap invariant lives here */ }
}
// Course is its own aggregate. Enrolment holds a CourseId, not a Course.
27. OOP versus functional programming — how does modern C# blend them?
Answer
OOP couples data with behaviour behind an encapsulated boundary and makes adding new types cheap. FP separates immutable data from pure transformations and makes adding new operations cheap. That trade-off is the "expression problem", and it is the real answer: choose polymorphism when the type set grows, and pattern matching over a closed set when the operations grow. Modern C# gives you both — records, switch expressions, LINQ and pattern matching sit inside an OO type system, and idiomatic code uses each where it fits.
Example — Insurance
Polymorphic when new products keep arriving (types vary):
public abstract class Policy { public abstract decimal Excess(Claim c); }
// A new product = a new class. No existing file is edited.
Pattern matching when the type set is closed and the operations keep arriving (operations vary):
public abstract record ClaimEvent
{
public sealed record Submitted(DateOnly On) : ClaimEvent;
public sealed record Assessed(decimal Amount) : ClaimEvent;
public sealed record Rejected(string Reason) : ClaimEvent;
}
static string Describe(ClaimEvent e) => e switch
{
ClaimEvent.Submitted s => $"Submitted on {s.On:d}",
ClaimEvent.Assessed a => $"Assessed at {a.Amount:C}",
ClaimEvent.Rejected r => $"Rejected: {r.Reason}",
_ => throw new ArgumentOutOfRangeException(nameof(e))
};
Example — Employee
A pure pipeline — no mutation, trivially testable and parallelisable:
static IReadOnlyList<Payslip> RunPayroll(IEnumerable<Employee> staff, TaxYear year) =>
staff.Where(e => e.IsActive)
.Select(e => new Payslip(e.Id, Gross(e), Tax(Gross(e), year)))
.OrderBy(p => p.EmployeeId)
.ToList();
static decimal Gross(Employee e) => e.AnnualSalary / 12; // pure
static decimal Tax(decimal gross, TaxYear y) => gross * y.Rate; // pure
Example — Student
Immutable state transitions, expressed functionally over a record:
public sealed record Enrolment(Guid StudentId, Guid CourseId, EnrolmentStatus Status)
{
public Enrolment Withdraw() => this with { Status = EnrolmentStatus.Withdrawn };
public Enrolment Complete(Grade g) => this with { Status = EnrolmentStatus.Completed, Grade = g };
public Grade? Grade { get; init; }
}
28. What are the OOP anti-patterns you actively look for in code review?
Answer
The five that cause the most damage: the God object (one class that knows everything — the tell is a file over ~500 lines with unrelated usings); the service locator (hiding dependencies from the constructor, so the compiler cannot tell you what a class needs); singleton abuse (global mutable state with no lifetime control and no test seam); the leaky abstraction (an interface whose signatures expose the first implementation's mechanics); and inheritance for code reuse (subclassing purely to inherit a helper method, with no substitutability).
Example — Insurance
God object, and the split:
// Anti-pattern: rating, persistence, documents, notifications, regulatory reporting.
public class PolicyManager { /* 2,400 lines */ }
// Split by reason to change.
public sealed class PremiumCalculator { }
public sealed class PolicyRepository { }
public sealed class PolicyDocumentGenerator { }
public sealed class RegulatoryReporter { }
Example — Employee
Service locator versus honest dependencies:
// Anti-pattern — the constructor lies about what this class needs.
public class PayrollService
{
private readonly IServiceProvider _sp;
public PayrollService(IServiceProvider sp) => _sp = sp;
public void Run() => _sp.GetRequiredService<ITaxWithholding>().Withhold(0m, default);
// Fails at runtime, not startup. Untestable without a full container.
}
// Honest — missing registrations fail at startup, and tests pass a fake.
public sealed class PayrollService(ITaxWithholding withholding) { }
Example — Student
Singleton abuse — hidden global state that makes tests order-dependent:
// Anti-pattern
public sealed class GradeCache
{
public static readonly GradeCache Instance = new();
private readonly Dictionary<Guid, Grade> _cache = new(); // shared, mutable, not thread-safe
}
// Fixed — a normal class with a container-managed singleton lifetime and a thread-safe store.
public sealed class GradeCache
{
private readonly ConcurrentDictionary<Guid, Grade> _cache = new();
}
builder.Services.AddSingleton<GradeCache>();