Generics & Collections
Master generics and collections for type-safe and efficient data management. This is a foundational concept in Microsoft application framework that professional developers rely on daily. The explanations below are written to be beginner-friendly while covering the depth and nuance that comes from real-world .NET experience. Take your time with each section and practice the examples
Understanding Generics
Generics allow you to define type-safe classes, methods, and interfaces without specifying the actual data type until runtime. This provides better performance and type safety.. This is an essential concept that every .NET developer must understand thoroughly. In professional development environments, getting this right can mean the difference between code that works reliably and code that breaks in production. The following sections break this down into clear, digestible pieces with practical examples you can try immediately
Generic Classes and Methods
// Generic class
public class GenericRepository<T>
{
private List<T> items = new List<T>();
public void Add(T item)
{
items.Add(item);
}
public T GetById(int id)
{
return items[id];
}
public List<T> GetAll()
{
return new List<T>(items);
}
public void Remove(T item)
{
items.Remove(item);
}
}
// Generic method
public static class Utility
{
public static void Swap<T>(ref T a, ref T b)
{
T temp = a;
a = b;
b = temp;
}
public static T Max<T>(T a, T b) where T : IComparable<T>
{
return a.CompareTo(b) > 0 ? a : b;
}
}
// Usage
GenericRepository<string> stringRepo = new GenericRepository<string>();
stringRepo.Add("Hello");
stringRepo.Add("World");
GenericRepository<int> intRepo = new GenericRepository<int>();
intRepo.Add(1);
intRepo.Add(2);
// Generic method usage
int x = 10, y = 20;
Utility.Swap(ref x, ref y);
Console.WriteLine($"x: {x}, y: {y}"); // x: 20, y: 10