Sobes.tech
Junior — Middle

Kas olete kasutanud üldist tüüpe oma projektides või ülesannetes?

sobes.tech AI

Vastus AI-lt

Generic types in C# allow creating classes, methods, and structures that work with any data types, ensuring type safety and code reusability.

For example, instead of creating a separate class to work with different data types, you can create a single generic class:

public class Repository<T>
{
    private List<T> items = new List<T>();

    public void Add(T item) => items.Add(item);
    public T Get(int index) => items[index];
}

// Usage:
var intRepo = new Repository<int>();
intRepo.Add(5);

var stringRepo = new Repository<string>();
stringRepo.Add("text");

In my projects, I have used generics to create universal collections, services, and utilities, which significantly reduced code duplication and increased flexibility.