C# — Generics
Generic class
public class Box<T>
{
public T Content { get; set; }
public Box(T content)
{
Content = content;
}
}
var intBox = new Box<int>(42);
var strBox = new Box<string>("Hello");
Generic method
public static T Max<T>(T a, T b) where T : IComparable<T>
{
return a.CompareTo(b) > 0 ? a : b;
}
Console.WriteLine(Max(10, 20)); // 20
Console.WriteLine(Max("a", "b")); // b
Generic constraints
public class Repository<T> where T : class, IEntity
{
public void Save(T entity) { }
public T FindById(int id) => default;
}
// Multiple constraints
public class Cache<T> where T : class, ICloneable, new()
{
public T CreateDefault() => new T();
}
Generic interface
public interface IRepository<T>
{
void Add(T item);
T GetById(int id);
IEnumerable<T> GetAll();
}
Mini Practice
Write C# code that:
- Creates a generic class
- Uses generic constraints
- Implements a generic interface
- Creates a generic method
Up Next
In the next lesson, you'll learn about LINQ — querying collections.
Related Topics
Frequently Asked Questions about Generics
What is Generics in C#?
Generics is a fundamental concept in C#. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Generics?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Generics.
Why is Generics important in C#?
Generics is essential for C# development. Understanding this concept will help you write better code and solve real-world problems more effectively.