📘 Introduction
In C#, Generics are one of the most powerful features introduced with the .NET Framework 2.0.
They allow you to define classes, methods, interfaces, and collections that can work with any data type — while still maintaining type safety and performance.
In simple words, Generics help you write code once and use it with any data type.
⚙️ What Are Generics?
Generics let you define a placeholder type (called a type parameter) that will be replaced with a specific type when you create an instance of a class or call a method.
This means you can write:
—all using the same generic List<T> class.
💡 Example Without Generics
If you want to add float
or double
values, you’ll have to write multiple methods for each data type.
This leads to code duplication and poor reusability.
⚙️ Example With Generics
✅ Output
Here, T
is a type parameter. It allows the Calculator
class to operate with any data type (int
, double
, string
, etc.).
🧱 Generic Method Example
You can also create generic methods inside normal classes.
✅ Output
Here, the method ShowData<T>()
can accept any data type without overloading.
📚 Generic Collections in C#
C# provides several built-in generic collections inside the System.Collections.Generic
namespace.
These are type-safe and more efficient than old non-generic collections like ArrayList
or Hashtable
.
Generic Collection | Description |
---|---|
List<T> | Dynamic array of type T |
Dictionary<TKey, TValue> | Key-value pair collection |
Queue<T> | FIFO (First-In-First-Out) collection |
Stack<T> | LIFO (Last-In-First-Out) collection |
Example:
✅ Output
🧩 Benefits of Generics in C#
Benefit | Description |
---|---|
Type Safety | Prevents type mismatches at compile time |
Performance | Avoids boxing/unboxing for value types |
Reusability | Write code once, use with any type |
Maintainability | Cleaner and less repetitive code |
🔄 Generic Constraints (Optional but Powerful)
Sometimes, you might want to restrict which data types can be used with your generic class.
Example:
Here, where T : class
means only reference types can be used.
🚀 Conclusion
Generics in C# make your code reusable, efficient, and type-safe.
They help developers build scalable and maintainable applications, especially in large projects using .NET Core or ASP.NET.
No comments:
Post a Comment