Collections and Generics
Collections and generics are important features in C# that allow you to work with groups of objects and provide type safety. They provide powerful and flexible ways to store, manipulate, and retrieve data. Let’s explore collections and generics in C#:
- Collections:
- Collections are classes that represent groups of objects.
- They provide various operations to add, remove, search, and iterate over the elements.
- C# offers several built-in collection classes, such as List<T>, Dictionary<TKey, TValue>, Queue<T>, Stack<T>, etc.
Example:
List<string> names = new List<string>();
names.Add(“Alice”);
names.Add(“Bob”);
names.Add(“Charlie”);
foreach (string name in names)
{
Console.WriteLine(name);
}
// Output:
// Alice
// Bob
// Charlie
- Generics:
- Generics provide a way to create reusable code that works with different types.
- They enable you to define classes, methods, and interfaces that can be parameterized with one or more types.
- Generics ensure type safety and avoid the need for casting.
Example:
public class Stack<T>
{
private List<T> items = new List<T>();
public void Push(T item)
{
items.Add(item);
}
public T Pop()
{
if (items.Count == 0)
throw new InvalidOperationException(“Stack is empty.”);
T item = items[items.Count – 1];
items.RemoveAt(items.Count – 1);
return item;
}
}
Stack<int> stack = new Stack<int>();
stack.Push(10);
stack.Push(20);
int value = stack.Pop();
Console.WriteLine(value); // Output: 20
- Advantages of Generics:
- Type safety: Generics ensure compile-time type checking, preventing type-related errors at runtime.
- Code reusability: Generics allow you to create generic classes, methods, and interfaces that work with different types without duplicating code.
- Performance: Generics provide better performance by eliminating the need for boxing/unboxing and avoiding unnecessary type conversions.
- Common Collection Classes:
- List<T>: Dynamic-size list of elements.
- Dictionary<TKey, TValue>: Key-value pairs with fast lookup based on the key.
- Queue<T>: FIFO (First-In, First-Out) collection.
- Stack<T>: LIFO (Last-In, First-Out) collection.
- LinkedList<T>: Doubly linked list.
- HashSet<T>: Unordered collection of unique elements.
- SortedSet<T>: Ordered collection of unique elements.
- and more…
Collections and generics in C# provide a powerful way to work with groups of objects in a type-safe and efficient manner. By leveraging these features, you can write reusable code, improve performance, and handle various data manipulation scenarios effectively.