Generic Collections
Introduction to Generic Collections in C#
Generic collections in C# are a part of the System.Collections.Generic namespace. They are a modern, faster and safer alternative to non-generic collections (System.Collections). Unlike non-generic collections, generic collections maintain type-safety, which means you don't have to box or unbox data.
Understanding Generic Collections
In C#, a generic collection is a collection that can store any datatype but maintains type safety. By using generic collections, you can take advantage of the strong typing feature without having to derive a new class or interface.
Generic collections in C# include, but are not limited to:
- List<T>
- LinkedList<T>
- Stack<T>
- Queue<T>
- HashSet<T>
- Dictionary<TKey, TValue>
List<T> in C#
A List<T> is a dynamic array, meaning its size can increase or decrease dynamically. List<T> provides methods and properties to add, insert, or remove items, and to find items.
List<int> numbers = new List<int>(); // Create a list of integers
numbers.Add(1); // Add an integer to the list
numbers.Add(2);
numbers.Add(3);
int firstNumber = numbers[0]; // Accessing elements by index
LinkedList<T> in C#
A LinkedList<T> is a doubly-linked list. Each node points to both the next node and the previous node. It is best used when you need to frequently add and remove items from the list.
LinkedList<string> words = new LinkedList<string>();
words.AddLast("Apple");
words.AddLast("Banana");
words.AddFirst("Mango");
Stack<T> in C#
A Stack<T>
is a Last-In-First-Out (LIFO) collection. It is used when you need a last-in, first-out access of items.
Stack<string> books = new Stack<string>();
books.Push("Book1");
books.Push("Book2");
string lastBook = books.Pop(); // "Book2"
Queue<T> in C#
A Queue<T> is a First-In-First-Out (FIFO) collection. It is used when you need first-in, first-out access of items.
Queue<string> tasks = new Queu<string>();
tasks.Enqueue("Task1");
tasks.Enqueue("Task2");
string firstTask = tasks.Dequeue(); // "Task1"
HashSet<T> in C#
A HashSet<T> is a collection of unique elements. It is used when you want to prevent duplicate elements from being inserted into the collection.
HashSet<int> uniqueNumbers = new HashSet<int>();
uniqueNumbers.Add(1);
uniqueNumbers.Add(2);
uniqueNumbers.Add(1); // this will not be added as 1 already exists
Dictionary<TKey, TValue> in C#
A Dictionary<TKey, TValue> is a collection of key-value pairs. It is used when you want to access values based on their corresponding keys.
Dictionary<string, string> capitals = new Dictionary<string, string>();
capitals.Add("France", "Paris");
capitals.Add("India", "New Delhi");
string capitalOfIndia = capitals["India"]; // "New Delhi"
Conclusion
Generic collections in C# provide a type-safe and efficient way to handle collections of data. By understanding how to use each type of generic collection, you can choose the right tool for your specific needs and write more efficient and safer code.