Generics in C# provide a way to define classes, interfaces, and methods that use placeholders for the types they store or operate on. This feature allows you to write more flexible and reusable code while maintaining type safety. By utilizing generics, you can avoid code duplication and enhance performance through more precise type constraints during compilation.
Basics of Generics
Generic Classes: These are classes that can work with any data type.
Generic Methods: These methods can accept any data type as a parameter.
Generic Interfaces: Interfaces that can be implemented by multiple types.
classProgram { staticvoidMain() { // Create a GenericList of integers GenericList<int> intList=newGenericList<int>(); intList.AddItem(1); intList.AddItem(2); intList.AddItem(3); intList.DisplayItems();
// Create a GenericList of strings GenericList<string> stringList=newGenericList<string>(); stringList.AddItem("Hello"); stringList.AddItem("World"); stringList.DisplayItems(); } }
Explanation of the Example
Generic Class (GenericList<T>): The ‘GenericList<T>’ class utilizes a type parameter ‘T’ to define a list capable of storing items of any type.
AddItem Method: The ‘AddItem’ method accepts a parameter of type ‘T’ and adds it to the internal list.
GetItem Method: The ‘GetItem’ method takes an integer index and returns the item located at that index in the internal list, ensuring type safety.
DisplayItems Method: The ‘DisplayItems’ method iterates through the internal list and prints each item to the console.
Main Method: In the main method, we create instances of ‘GenericList<int>’ and ‘GenericList<string>’, demonstrating the flexibility of generics in handling various data types. Items are added to both lists, and their contents are displayed.
Benefits of Using Generics
Type Safety: Generics ensure type safety by allowing you to catch type-related errors at compile time rather than at runtime.
Code Reusability: Generics enable you to write a single class or method that can operate with different data types, promoting code reuse and reducing redundancy.
Performance: Generics enhance performance by eliminating the need for boxing and unboxing when working with value types, as well as reducing the need for type casting.
Consistency: Generics provide a consistent approach to handling collections of data, which makes your code more readable and maintainable.