07 Feb 2024
Intermediate
Here are some common use cases for generics:
-
Collections: The
System.Collections.Genericnamespace provides various generic collection classes likeList<T>,Dictionary<TKey, TValue>, andQueue<T>, offering type-safe and efficient data storage and retrieval.-
List:
using System.Collections.Generic; List<int> numbers = new List<int>(); numbers.Add(1); numbers.Add(2); numbers.Add(3); -
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); -
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.-
Swap:
public void Swap<T>(ref T a, ref T b) { T temp = a; a = b; b = temp; } -
Max:
public T Max<T>(T a, T b) where T : IComparable<T> { return a.CompareTo(b) > 0 ? a : b; } -
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.
-
IComparable:
public interface IComparable<T> { int CompareTo(T other); } -
IEnumerable:
public interface IEnumerable<T> { IEnumerator<T> GetEnumerator(); } -
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); }
-