Medium csharp

Interface — IRepository pattern

Problem

Define IRepository with GetById and implement in-memory repo.

Hints
  • Add GetById to interface and implement in class

Your practice code

Ready — edit the code above and click Run.

Solution

using System;
using System.Collections.Generic;

interface IRepository {
    string GetById(int id);
}
class InMemoryRepo : IRepository {
    private readonly Dictionary<int, string> _data = new() { [1] = "Item1" };
    public string GetById(int id) => _data.TryGetValue(id, out var v) ? v : null;
}
class Program {
    static void Main() {
        IRepository repo = new InMemoryRepo();
        Console.WriteLine(repo.GetById(1));
    }
}

Try solving on your own first, then reveal the official answer.

Explanation

Program to interface, not implementation—SOLID dependency inversion in .NET interviews.

Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details