Technical Definition
Generics allow developers to create strongly typed components by specifying type parameters that are replaced with actual data types at compile time.
Why Generics Are Needed
Before generics, collections stored data as object, which caused:
- Runtime casting errors
- Boxing and unboxing overhead
- Poor type safety
Generics solve these problems.
Simple Example (Generic Class)
public class MyGeneric<T>
{
public T Data { get; set; }
}
MyGeneric<int> obj1 = new MyGeneric<int>();
obj1.Data = 100;
MyGeneric<string> obj2 = new MyGeneric<string>();
obj2.Data = "Hello";
- ✔ Compile-time type checking
- ✔ No casting required
public class MyGeneric<T>
{
public T Data { get; set; }
}
MyGeneric<int> obj1 = new MyGeneric<int>();
obj1.Data = 100;
MyGeneric<string> obj2 = new MyGeneric<string>();
obj2.Data = "Hello";Generic Method Example
public void Print<T>(T value)
{
Console.WriteLine(value);
}
Print<int>(10);
Print<string>("C# Generics");
public void Print<T>(T value)
{
Console.WriteLine(value);
}
Print<int>(10);
Print<string>("C# Generics");Generic Collection Example
List<int> numbers = new List<int> { 1, 2, 3 };
List<string> names = new List<string> { "John", "Alex" };
- ✔ Type safe
- ✔ Faster than non-generic collections
List<int> numbers = new List<int> { 1, 2, 3 };
List<string> names = new List<string> { "John", "Alex" };Generic Constraints
public class Repository<T> where T : class
{
}
public class Repository<T> where T : class
{
}Common Constraints
| Constraint | Description |
|---|---|
| where T : class | Reference type |
| where T : struct | Value type |
| where T : new() | Default constructor |
| where T : BaseClass | Inheritance |
| where T : interface | Interface implementation |
Advantages of Generics
- ✔ Strong type safety
- ✔ Reusable code
- ✔ Better performance
- ✔ Cleaner, maintainable code
One-Line Interview Answer
Generics in C# allow the creation of type-safe and reusable code by defining placeholders for data types that are specified at runtime or compile time.

0 Comments:
Post a Comment