← Foundations path
.NETFoundations 3 / 37

Constructor

“What is a constructor, and why validate inside it?”

The code that runs once, the moment an object is built. The one place that can refuse a bad object.

See it

your codeIn memorymade while the app runsBefore the fixheapnew Loan(500000, 0, 60)constructor1. no check2. copy values incar = 0x1ALoan @ 0x1AAmount 0Rate 0Months 0Emi(): DivideByZero
1 / 9Before the fix. new Loan(500000, 0, 60) asks for a loan with rate 0, say from a typo in a form.

In plain words

A constructor is the code that runs once, the moment builds an object. Its job is to give the object its starting values, and to refuse bad ones. If it throws an error, the object is never handed to anyone, so a broken Loan can never exist.

Say it in the interview

In the lending API

The same file before and after the fix, plus its test. Press Next line to walk through them.

Lending.sln · where these 3 files sit
  • src/Domain/Servicing/
  • tests/Domain.UnitTests/Servicing/
Diagram · step 3Then the constructor runs, once. With no check, it copies the rate of 0 straight in.
your codeIn memorymade while the app runsBefore the fixheapnew Loan(500000, 0, 60)constructor1. no check2. copy values incar = 0x1ALoan @ 0x1AAmount 0Rate 0Months 0Emi(): DivideByZero
Loan.old.cs · line 10 · 1 of 3The constructor: same name as the class, no return type. It runs once, after has made the empty object.

What they ask next

Interviewers check that you can explain every line. Tap a question to open it.

Traps

With AI tools

Canva's interview guide says it grades whether you find and fix the issues in AI-written code and make it production-standard. A class that accepts any value is the kind of gap they mean. Before you accept generated code, ask: what values can reach this object, and what breaks later if a bad one does?

Read more: Microsoft Learn: constructors · Static constructors · Primary constructors · EF Core: entity types with constructors · ArgumentOutOfRangeException.ThrowIfNegativeOrZero · Canva: AI in our interviews