Definition - What does Generics mean?
Generics refer to a feature in C# that allows defining a class or method with type as a parameter.
Generics allow for designing a classes and methods whose types are specified only at the time of declaration and instantiation. This enables development of universal classes and methods that help in improving performance, productivity and type-safety.
Generics are often used in creating collection classes for implementing concepts such as lists, hash tables, queues, etc. These classes manage a set of objects and encapsulate operations that are not specific to a particular data type.
Generics are also known as parametric polymorphism.
Techopedia explains Generics
Generics were introduced in C# 2.0 as a part of Common Language Runtime of .NET to overcome the limitation in implementing generalization in earlier versions. Generalization was accomplished by casting types to and from universal base type, System.Object that was not type-safe and required casting, which results in a hit to performance.
Some of the benefits in using generics include:
- Casting is not required for accessing each element in the collection
- Client code that uses generics is type-safe during execution by preventing the usage of data whose type is different from the one used in the declaration
- Code is not duplicated for multiple types of data
The List<T> collection class is an example for generic class provided in the .NET Framework Class library that can be used to add, delete and search an item of any type (T) that is passed as parameter to it. When the List class is instantiated with a type parameter in the client code, it would be similar to a concrete class implemented with same type.
Generics are similar to C++ templates in concept but differ mainly in implementation.