07 Feb 2024




Intermediate

Here are some common use cases for generics:

  • Collections: The System.Collections.Generic namespace provides various generic collection classes like List<T>, Dictionary<TKey, TValue>, and Queue<T>, offering type-safe and efficient data storage and retrieval.

    1. List:

      using System.Collections.Generic;
      
      List<int> numbers = new List<int>();
      numbers.Add(1);
      numbers.Add(2);
      numbers.Add(3);
      
    2. Dictionary<TKey, TValue>:

      using System.Collections.Generic;
      
      Dictionary<string, int> ages = new Dictionary<string, int>();
      ages.Add("John", 30);
      ages.Add("Alice", 25);
      ages.Add("Bob", 35);
      
    3. Queue:

      using System.Collections.Generic;
      
      Queue<string> tasks = new Queue<string>();
      tasks.Enqueue("Task 1");
      tasks.Enqueue("Task 2");
      tasks.Enqueue("Task 3");
      
  • Methods: You can define generic methods that operate on different data types, such as a Swap<T>(T a, T b) method that swaps the values of two variables regardless of their type.

    1. Swap:

      public void Swap<T>(ref T a, ref T b)
      {
          T temp = a;
          a = b;
          b = temp;
      }
      
    2. Max:

      public T Max<T>(T a, T b) where T : IComparable<T>
      {
          return a.CompareTo(b) > 0 ? a : b;
      }
      
    3. PrintArray:

      public void PrintArray<T>(T[] array)
      {
          foreach (T item in array)
          {
       	   Console.WriteLine(item);
          }
      }
      
  • Interfaces: Generic interfaces can define contracts for generic types, ensuring consistency and type safety across different implementations.

    1. IComparable:

      public interface IComparable<T>
      {
          int CompareTo(T other);
      }
      
    2. IEnumerable:

      public interface IEnumerable<T>
      {
          IEnumerator<T> GetEnumerator();
      }
      
    3. IList:

      public interface IList<T> : ICollection<T>
      {
          T this[int index] { get; set; }
          int IndexOf(T item);
          void Insert(int index, T item);
          void RemoveAt(int index);
      }
      
c-sharp
use-cases
generics