C# Generics Explained: Type-Safe Reusable Code
Generics let you write reusable code while keeping compile-time type safety. They are used throughout .NET, from List<T> to dictionaries and many framework APIs.
๐งฉ What Is a Generic Type?
A generic type uses a type parameter instead of hard-coding a specific data type.
public class Box<T>
{
public T Value { get; set; }
}
var numberBox = new Box<int> { Value = 10 };
var textBox = new Box<string> { Value = "Hello" };
The same class works with different types without casts.
โก Generic Methods
Methods can also define their own type parameters.
static T First<T>(T a, T b)
{
return a;
}
int number = First(10, 20);
string text = First("A", "B");
The compiler can infer the type argument from the values passed to the method.
๐ Generic Constraints
Constraints tell the compiler what a type parameter must support.
static T Create<T>() where T : new()
{
return new T();
}
Other common constraints include class, struct, a base class, or an interface.
๐ง Why Use Generics?
- Improve compile-time type safety.
- Reduce repetitive code.
- Avoid unnecessary casting.
- Make reusable libraries easier to design.
- Often improve performance by avoiding boxing for value types.
๐ฆ Generics in .NET Collections
Common generic collections include List<T>, Dictionary<TKey,TValue>, HashSet<T>, Queue<T>, and Stack<T>.
๐ซ A Common Mistake
Do not make everything generic simply because you can. A generic abstraction should represent a real reusable relationship between types.
๐งช Generic Interface Example
public interface IRepository<T>
{
T GetById(int id);
void Add(T item);
}
This pattern can provide a strongly typed contract for different domain entities.
๐ฏ Key Takeaway
Generics allow C# code to be reusable without giving up type safety. Learn them well and many .NET APIs become much easier to understand.
Continue with ๐ป C# Tutorials.
Ask AlgoLassi and get an answer plus the tutorials worth studying next.
๐ฌ Comments
Sign in with Google to publish immediately, or comment anonymously and wait for approval.
Comments will appear here when available.