← Foundations path
.NETFoundations 11 / 37

List<T> and IReadOnlyList<T>

“How does a List of a base type hold different objects, and why return IReadOnlyList?”

A list holds references to objects. A list of Contract can hold Loans and Leases side by side, and a loop calls each one's own method.

See it

1/9Before. One variable per contract. But how many contracts are due today? 3? 30,000?

In plain words

holds any number of items and grows as you . T is a placeholder: you write the real type in the angle brackets, like . For classes, the list holds references, so a list of Contract can point at Loan and Lease objects side by side. A loop visits each one, and a call runs each object's own version. When you give a list to other code, give so it can read but not change it.

Say it in the interview

In the lending API

Building a mixed list, looping it, and handing it out safely. Press Next line to walk through them.

Lending.sln · where these 2 files sit
  • src/Billing/
Diagram · step 3The fix: . The type in <> says what it holds. It starts empty (Count 0) and grows.
BillingRun.cs · line 1 · 1 of 5An empty list that may hold anything that is a Contract.

What they ask next

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

Traps

Read more: Microsoft Learn: List<T> · IReadOnlyList<T> · Generics in C#