English
Summary
Conclusions
Generics let you write code once for many types without boxing or casts, and the compiler checks the types. Generic methods infer type arguments from the call arguments, generic classes form closed types, and where constraints let you use the capabilities of a type parameter; generic math extends this to arithmetic. Collections are chosen by their main operations and their complexity: List<T> for lists with index access, Dictionary<TKey, TValue> and HashSet<T> for fast lookup, Queue<T>, Stack<T>, and PriorityQueue for processing order, and sorted collections for iterating by key. The IEnumerable<T> and IReadOnlyList<T> interfaces make code flexible and protect internal data, and yield return iterators create lazy sequences.
Self-check questions
- What are the drawbacks of
objectcollections such asArrayList? - What is a type parameter? How does the compiler infer a type argument?
- How does an open generic type differ from a closed one?
- What does
default(T)return? - What are
whereconstraints for? Give examples. - What is generic math?
- How do you choose a collection? What do O(1), O(log n), and O(n) mean?
- How does
Countdiffer fromCapacityinList<T>? - How does lookup by key work in
Dictionary<TKey, TValue>? What are the requirements for a key? - Why is
TryGetValuebetter than the dictionary indexer? - What set operations does
HashSet<T>support? - How do
Queue<T>,Stack<T>, andPriorityQueue<TElement, TPriority>differ? - When does it make sense to use
LinkedList<T>? - Why return collections as
IReadOnlyList<T>? - How does an iterator with
yield returnwork? - Why can’t you modify a collection in a
foreachloop?
Useful links
- Generics: https://learn.microsoft.com/dotnet/csharp/fundamentals/types/generics
- Type parameter constraints: https://learn.microsoft.com/dotnet/csharp/language-reference/keywords/where-generic-type-constraint
- .NET collections: https://learn.microsoft.com/dotnet/standard/collections/
- Selecting a collection: https://learn.microsoft.com/dotnet/standard/collections/selecting-a-collection-class
- Iterators: https://learn.microsoft.com/dotnet/csharp/iterators
PriorityQueue<TElement, TPriority>: https://learn.microsoft.com/dotnet/api/system.collections.generic.priorityqueue-2