Bài tập C#

Generic In-Memory Repository

Generics eliminate casts while sharing one implementation across entity types.

How it works

Store any entity type through a reusable generic class.

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]); }
}
Expected output
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.