C# Practice Exercises

Generic In-Memory Repository

Store any entity type through a reusable generic class.

Introduction

Generics eliminate casts while sharing one implementation across entity types.

The repository's List<T> can only contain the type selected when the repository is constructed.

Runnable C# example

C#
Run code →
Program.cs
using System;
using System.Collections.Generic;
class Repository<T>
{
    private readonly List<T> _items = new();
    public void Add(T item) => _items.Add(item);
    public IReadOnlyList<T> All => _items;
}
class Program
{
    static void Main() { var repo = new Repository<string>(); repo.Add("C#"); Console.WriteLine(repo.All[0]); }
}
Result of running the code
C#

Practice with the debugger

Set a breakpoint on an important assignment or condition, click Debug, and inspect the local values before stepping to the next line.

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges