The Anubhav portal was launched in March 2015 at the behest of the Hon'ble Prime Minister for retiring government officials to leave a record of their experiences while in Govt service .
Generics in C# allow you to define classes, interfaces, methods, or delegates with a placeholder for the data type. This means you can write code that works with
any data type while maintaining type safety and avoiding runtime casting.
Why Generics Are Useful:
Benefit
Explanation
Type Safety
Errors are caught at compile time instead of runtime.
Code Reusability
You can write logic once and reuse it with different types.
Performance
Avoids boxing/unboxing with value types.
Clarity
Clear intent — you know what type is being used in advance.
Example: Without Generics
public class Box
{
public object Item { get; set; }
}
var intBox = new Box();
intBox.Item = 123;
int value = (int)intBox.Item; // Requires casting
Problems:
No compile-time type check.
Requires casting → possible runtime exceptions.
With Generics:
public class Box<T>
{
public T Item { get; set; }
}
var intBox = new Box<int>();
intBox.Item = 123;
int value = intBox.Item; // No casting, type-safe
Generic Method Example:
public T GetFirst<T>(List<T> items)
{
return items.First();
}
Can be called as:
int first = GetFirst(new List<int> { 1, 2, 3 });
string firstStr = GetFirst(new List<string> { "a", "b" });
.NET Built-in Examples:
List<T>
Dictionary<TKey, TValue>
Task<T>
Nullable<T> (i.e., int?)
Summary:
Generics allow you to write:
Flexible, yet strongly typed code
Without duplicating logic for different types
And with better performance and safety
Let me know if you want to see:
Generic constraints (where T : class, etc.)
Generic interfaces
Comparisons with templates in C++
Join MindStick Community
You need to log in or register to vote on answers or questions.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Generics in C# allow you to define classes, interfaces, methods, or delegates with a placeholder for the data type. This means you can write code that works with any data type while maintaining type safety and avoiding runtime casting.
Why Generics Are Useful:
Example: Without Generics
Problems:
With Generics:
Generic Method Example:
Can be called as:
.NET Built-in Examples:
List<T>Dictionary<TKey, TValue>Task<T>Nullable<T>(i.e.,int?)Summary:
Generics allow you to write:
Let me know if you want to see:
where T : class, etc.)