What Are Generics in C#: Simple Explanation and Example
generics allow you to create classes, methods, or data structures that work with any data type while keeping type safety. They help you write flexible and reusable code without losing the benefits of strong typing.How It Works
Generics in C# work like a recipe that can be used with different ingredients. Instead of writing separate code for each data type, you write one generic version that adapts to the type you choose when you use it. This means you can create a list, a box, or a method that works with integers, strings, or any other type without rewriting the code.
Think of it like a toolbox with adjustable tools. You don’t need a different hammer for every nail size; you just adjust the hammer to fit. Similarly, generics let you write one piece of code that fits many types, making your programs cleaner and safer because the compiler checks that you use the right types.
Example
This example shows a generic class called Box that can hold any type of item. You create a Box for integers or strings without changing the class code.
using System; public class Box<T> { private T item; public void Add(T newItem) { item = newItem; } public T Get() { return item; } } class Program { static void Main() { Box<int> intBox = new Box<int>(); intBox.Add(123); Console.WriteLine(intBox.Get()); Box<string> strBox = new Box<string>(); strBox.Add("Hello Generics"); Console.WriteLine(strBox.Get()); } }
When to Use
Use generics when you want to write code that works with different data types but behaves the same way. They are perfect for collections like lists, stacks, or queues where the type of items can vary. Generics help avoid code duplication and reduce errors by catching type mismatches during compilation.
For example, if you build a library for managing data, generics let users store any kind of data without rewriting your code. They also improve performance by avoiding unnecessary conversions or boxing of data.
Key Points
- Generics provide type safety without losing flexibility.
- They reduce code duplication by allowing one implementation for many types.
- Generics improve performance by avoiding runtime type checks.
- Commonly used in collections and reusable components.