Chapter 6.3: Working with .NET Classes: Understanding System.Collections and System.Collections.Generic
Introduction:
In the previous article, Chapter 6.2, we explored the System.Text and System.Text.Encoding namespaces, which are important for working with text and character encodings in C# applications. In this article, we'll discuss the System.Collections and System.Collections.Generic namespaces, which provide classes for working with collections of objects. In the next article, we'll dive into the System.Linq namespace, which offers powerful querying capabilities for collections.
System.Collections Namespace:
The System.Collections namespace provides non-generic collection classes, such as ArrayList, Hashtable, and Queue. These classes store objects, but they don't enforce type safety:
ArrayList list = new ArrayList(); list.Add(42); list.Add("Hello, world!"); foreach (object item in list) { // Process item }
System.Collections.Generic Namespace:
The System.Collections.Generic namespace offers type-safe, generic collection classes, such as List<T>, Dictionary<TKey, TValue>, and Queue<T>. These classes provide better performance and type safety compared to their non-generic counterparts:
List<int> list = new List<int>(); list.Add(42); list.Add(123); foreach (int item in list) { // Process item }
Common Generic Collection Classes:
Some common generic collection classes in the System.Collections.Generic namespace include:
- List<T>: A dynamic array that automatically resizes as elements are added or removed.
- Dictionary<TKey, TValue>: A collection of key-value pairs, where each key is unique.
- HashSet<T>: A collection of unique elements with no specific order.
- Queue<T>: A first-in, first-out (FIFO) collection.
- Stack<T>: A last-in, first-out (LIFO) collection.
Dictionary<string, int> dictionary = new Dictionary<string, int>(); dictionary.Add("one", 1); dictionary.Add("two", 2); foreach (KeyValuePair<string, int> kvp in dictionary) { Console.WriteLine($"{kvp.Key}: {kvp.Value}"); }
Conclusion:
In this article, we discussed the System.Collections and System.Collections.Generic namespaces, which provide classes for working with collections of objects in C# applications. Understanding these classes will help you develop efficient and versatile applications. In the next article, we'll dive into the System.Linq namespace, which offers powerful querying capabilities for collections. Stay tuned for more insights into working with .NET classes!
Comments
Post a Comment