Your corner store already has products, and those products live somewhere: today, a collection in memory. Tomorrow you will want them in a file or a database. If every part of your program knows exactly how they are stored, that change forces you to touch all of those parts.
The Repository pattern exists so that change costs you one line instead of a week. It is the last pattern in this part, and the one you will see most in real projects.
The problem: everybody knows the storage
Look at this program. The products live in a Dictionary and every function receives it directly:
var products = new Dictionary<int, Product>
{
[1] = new Product(1, "Coffee", 4.50m),
[2] = new Product(2, "Bread", 1.25m),
};
ShowProduct(products, 1);
ShowProduct(products, 9);
ApplyDiscount(products, 2, 20m);
ShowProduct(products, 2);
static void ShowProduct(Dictionary<int, Product> products, int id)
{
if (!products.TryGetValue(id, out var product))
{
Console.WriteLine($"Product {id} does not exist");
return;
}
Console.WriteLine($"{product.Name}: {product.Price:0.00}");
}
static void ApplyDiscount(Dictionary<int, Product> products, int id, decimal percent)
{
if (!products.TryGetValue(id, out var product))
{
return;
}
product.Price = product.Price * (1 - percent / 100m);
}
class Product
{
public Product(int id, string name, decimal price)
{
Id = id;
Name = name;
Price = price;
}
public int Id { get; }
public string Name { get; }
public decimal Price { get; set; }
}
Coffee: 4.50
Product 9 does not exist
Bread: 1.00
It works. The trouble starts when conditions change. If tomorrow the products come from a database, there is no Dictionary to pass around. Every function that receives it has to be rewritten, and meanwhile you cannot test ApplyDiscount without building that whole dictionary. The business logic (take a percentage off) is mixed with the detail of where things are stored.
The pattern: an interface between your logic and your data
A repository is an object that behaves like a collection of products. Whoever uses it asks for things like “give me product 1” or “save this product”, and does not know or care where they are. You build it in two steps.
First, the interface: the contract of what can be done.
interface IProductRepository
{
Product? GetById(int id);
IReadOnlyList<Product> GetAll();
void Add(Product product);
void Update(Product product);
}
The ? in Product? says the result can be null, meaning that product may not exist. IReadOnlyList<Product> is a list the receiver can read but not modify, so nobody changes the repository’s contents from the outside.
Second, an implementation. The first one keeps everything in memory, with the Dictionary you already know:
class InMemoryProductRepository : IProductRepository
{
private readonly Dictionary<int, Product> _products = new();
public Product? GetById(int id)
{
return _products.TryGetValue(id, out var product) ? product : null;
}
public IReadOnlyList<Product> GetAll()
{
return new List<Product>(_products.Values);
}
public void Add(Product product)
{
_products.Add(product.Id, product);
}
public void Update(Product product)
{
_products[product.Id] = product;
}
}
The dictionary is now private. Nobody outside this class knows it exists.
The rest of the code depends on the interface
This is the part that changes the design. A service that uses products receives IProductRepository through its constructor, not a dictionary or the concrete class:
IProductRepository repository = new InMemoryProductRepository();
repository.Add(new Product(1, "Coffee", 4.50m));
repository.Add(new Product(2, "Bread", 1.25m));
var catalog = new CatalogService(repository);
catalog.ShowProduct(1);
catalog.ShowProduct(9);
catalog.ApplyDiscount(2, 20m);
catalog.ShowProduct(2);
Console.WriteLine($"Products in the catalog: {repository.GetAll().Count}");
class Product
{
public Product(int id, string name, decimal price)
{
Id = id;
Name = name;
Price = price;
}
public int Id { get; }
public string Name { get; }
public decimal Price { get; set; }
}
interface IProductRepository
{
Product? GetById(int id);
IReadOnlyList<Product> GetAll();
void Add(Product product);
void Update(Product product);
}
class InMemoryProductRepository : IProductRepository
{
private readonly Dictionary<int, Product> _products = new();
public Product? GetById(int id)
{
return _products.TryGetValue(id, out var product) ? product : null;
}
public IReadOnlyList<Product> GetAll()
{
return new List<Product>(_products.Values);
}
public void Add(Product product)
{
_products.Add(product.Id, product);
}
public void Update(Product product)
{
_products[product.Id] = product;
}
}
class CatalogService
{
private readonly IProductRepository _repository;
public CatalogService(IProductRepository repository)
{
_repository = repository;
}
public void ShowProduct(int id)
{
var product = _repository.GetById(id);
if (product == null)
{
Console.WriteLine($"Product {id} does not exist");
return;
}
Console.WriteLine($"{product.Name}: {product.Price:0.00}");
}
public void ApplyDiscount(int id, decimal percent)
{
var product = _repository.GetById(id);
if (product == null)
{
return;
}
product.Price = product.Price * (1 - percent / 100m);
_repository.Update(product);
}
}
Coffee: 4.50
Product 9 does not exist
Bread: 1.00
Products in the catalog: 2
The output is the same as before, but the design is different. CatalogService does not mention Dictionary anywhere. It only knows the interface.
Look at _repository.Update(product) at the end of ApplyDiscount. With the in-memory implementation it is not needed, because product is a reference to the same object that sits inside the dictionary, so changing the price already changed it there. A database does not work that way: what you get back is a copy, and if you do not say “save this change”, the change is lost. Write the service for the repository that is coming, not the one you have today.
What you gain
Changing the storage means changing one line: the one that says new InMemoryProductRepository(). If tomorrow you write a FileProductRepository class that implements the same interface, CatalogService never finds out. Real applications use a database for this, usually through a library like Entity Framework Core (EF Core), which you will meet when you get there. The structure is the same: a class that implements the interface and talks to the database, and a service that never sees it.
You also gain in testing. You can give CatalogService an in-memory repository with two made-up products and check that ApplyDiscount works, with no database and no files.
When NOT to use it
Repository adds an interface, a class and one more level of indirection. That has a cost, and sometimes it is not worth it.
- If your program has one list used in one place, a repository is ceremony. Use the list.
- If you are not going to change the storage or test the logic separately, the interface gives you nothing today. You can introduce it when that need shows up; it is not hard to add later.
- Do not copy every
Dictionarymethod into the interface. A repository exposes what your business needs (GetById,Add), not everything the storage knows how to do. - Some teams using EF Core decide not to wrap it in their own repository, because it already offers something similar. It is a real debate and you do not need to settle it now; I mention it so you do not think this pattern is mandatory.
As always in this part, the pattern is an answer to a problem. If the problem does not exist in your program yet, leave it for when it does.
Exercise
Add a method bool Remove(int id) to the interface that removes a product and returns true if it existed and false if not. Implement it in InMemoryProductRepository (hint: Dictionary has a Remove method that already returns that bool). Then add these lines at the end of the chapter’s Program.cs to try it:
Console.WriteLine(repository.Remove(2));
Console.WriteLine(repository.Remove(2));
Console.WriteLine(repository.GetAll().Count);
Suggested solution
In the interface, one new method:
interface IProductRepository
{
Product? GetById(int id);
IReadOnlyList<Product> GetAll();
void Add(Product product);
void Update(Product product);
bool Remove(int id);
}
In InMemoryProductRepository, the implementation:
public bool Remove(int id)
{
return _products.Remove(id);
}
With the rest of the program as it was, the three test lines print:
True
False
1
The first call removes the bread and returns true. The second no longer finds it and returns false. One product is left. And CatalogService did not change a single line.
Recap
- A repository is an object that behaves like a collection of your data and hides where it is stored.
- You build it with an interface (
IProductRepository) and one or more implementations (in memory today, a database tomorrow). - The rest of the program receives the interface through the constructor and does not know the storage.
- Do it when you need to change the storage or test the logic separately. Do not do it for a list used in a single place.
What’s next
With this chapter you close Part 3: SOLID and five patterns so your code can take change. Part 4 covers what nobody tells you: how to use Git and GitHub, how to read documentation, how to ask for help well, and how to use AI without giving up the learning.
If something was unclear or you want to share your exercise, DM me on Instagram or come by the Discord community.
