Lesson 23/30

Tutorials C# Mastery

Generics & Constraints: Building Type-Safe Libraries

On this page

Generics & Constraints

Generics allow you to write code that works with any type while maintaining 100% type safety. This eliminates the need for "Object" casting and prevents the performance penalty of Boxing and Unboxing.

1. Generic Classes & Methods

Instead of creating IntRepository, StringRepository, etc., you create ONE repository that takes a type T.

public class Repository<T> 
{
    private List<T> _data = new();
    public void Add(T item) => _data.Add(item);
}

2. Constraints: The Guardrails

What if your repository ONLY works for classes that have a database ID? You use where constraints to restrict which types can be used.

public class BaseEntity { public int Id { get; set; } }

// T MUST be a class, MUST have a parameterless constructor, 
// and MUST inherit from BaseEntity.
public class SecureRepo<T> where T : BaseEntity, new() 
{
    public void LogId(T item) => Console.WriteLine(item.Id);
}

3. The Benefits: Speed

Because the compiler generates a specific version of your class for every value type (like int), generics are significantly faster than using object. No casting is required, and no memory is wasted.

4. Interview Mastery

Q: "What is Variance (Covariance and Contravariance) in Generics?"

Architect Answer: "Variance defines whether you can use a more derived type (Covariance) or a more generic type (Contravariance) than originally specified. In C#, we use the `out` and `in` keywords on interfaces. `IEnumerable` is Covariant—it means you can safely pass a `List` to a method expecting an `IEnumerable` because you are only 'reading' data out. If you were 'writing' data in, this would be illegal. Mastery of Variance is what allows generic libraries to feel 'seamless' and 'natural' to the developer."

Questions on this lesson 0

Sign in to ask a question or upvote helpful answers.

No questions yet — be the first to ask!

C# Mastery
Course syllabus
1. Modern C# & Framework Fundamentals
2. Control Flow & Logical Structures
3. Object-Oriented Mastery
4. Functional C# & Collections
5. Asynchronous & Parallel Programming
6. Advanced Engineering & High Performance
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