← Foundations path
.NETFoundations 13 / 37

State and stateless

“What is a stateless class, and why should shared services be stateless?”

What an object remembers between one method call and the next, and why shared code should remember nothing.

See it

Statefulremembers between callsStatelessremembers nothingLoan @ 0x1AAmount 500000Rate 9.5Months 60car.Emi()= 10,500.93static class Emino fieldsnothing to keepMonthly(500000, 9.5, 60)= 10,500.93request Arequest BRate → 1211,122.22request Arequest B10,500.9310,500.93answer depends on the pastdepends on inputs only
1 / 11State is the data an object keeps between calls. This loan remembers Amount, Rate and Months.

In plain words

State is what an object remembers between one call and the next. A loan remembers its rate, so car.Emi() gives a different answer after the rate changes. A stateless class remembers nothing: works only from what you pass in, so the same inputs always give the same answer. Nothing remembered means nothing to mix up, so one copy can serve every user at once.

Say it in the interview

In the lending API

The stateless calculator and two tests: one shows state changing an answer, one shows no state at all. Press Next line to walk through them.

Lending.sln · where these 3 files sit
  • src/Domain/Common/
  • tests/Domain.UnitTests/
    • Servicing/
    • Common/
Diagram · step 5 has no fields. Everything it needs comes in as inputs, and nothing is kept after.
Statefulremembers between callsStatelessremembers nothingLoan @ 0x1AAmount 500000Rate 9.5Months 60car.Emi()= 10,500.93static class Emino fieldsnothing to keepMonthly(500000, 9.5, 60)= 10,500.93request Arequest BRate → 1211,122.22request Arequest B10,500.9310,500.93answer depends on the pastdepends on inputs only
Emi.cs · line 4 · 1 of 6No fields anywhere in this class, so there is nothing to remember. means you call it on the class itself, with no . More on .

What they ask next

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

Traps

With AI tools

An AI tool can add a "handy" field to a shared service, like remembering the last loan it worked on. It compiles and passes a one-user test. Interviews now include reviewing and explaining AI-written code, and "this field makes a shared service stateful" is the catch they expect.

Read more: Microsoft Learn: static classes · Microsoft Learn: DI service lifetimes · Microsoft Learn: Parallel.For