Generics

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.

Example

using System;
using System.Collections.Generic;

class GenericList<T>
{
  private List<T> items = new List<T>();

    // Add item to the list
  public void AddItem(T item)
  {
      items.Add(item);
  }

    // Get item by index
  public T GetItem(int index)
  {
      return items[index];
  }

    // Display all items
  public void DisplayItems()
  {
      foreach (var item in items)
      {
          Console.WriteLine(item);
      }
  }
}

class Program
{
  static void Main()
  {
      // Create a GenericList of integers
      GenericList<int> intList = new GenericList<int>();
      intList.AddItem(1);
      intList.AddItem(2);
      intList.AddItem(3);
      intList.DisplayItems();

        // Create a GenericList of strings
      GenericList<string> stringList = new GenericList<string>();
      stringList.AddItem("Hello");
      stringList.AddItem("World");
      stringList.DisplayItems();
  }
}

Explanation of the Example

  1. Generic Class (GenericList<T>):
    The ‘GenericList<T>’ class utilizes a type parameter ‘T’ to define a list capable of storing items of any type.
  2. AddItem Method:
    The ‘AddItem’ method accepts a parameter of type ‘T’ and adds it to the internal list.
  3. GetItem Method:
    The ‘GetItem’ method takes an integer index and returns the item located at that index in the internal list, ensuring type safety.
  4. DisplayItems Method:
    The ‘DisplayItems’ method iterates through the internal list and prints each item to the console.
  5. 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.
Post a comment

Leave a Comment

Scroll to Top