Generics in C# (List , Dictionary )
Originally published at https://allcoderthings.com/en/article/csharp-generics-list-t-dictionary-tkey-tvalue In C#, generics are used to increase type safety and flexibility. Generic classes and collections eliminate the need for runtime type casting and avoid unnecessary boxing and unboxing operations, improving performance and reducing the risk of errors. Before generics were introduced, collections such as ArrayList stored elements as object . When a value type like int was added to an ArrayList , it had to be boxed (converted to object ), and later unboxed when retrieved. This boxing/unboxing process caused additional memory allocations and performance overhead. With generic collections like List<T> and Dictionary<TKey,TValue> , elements are stored in their actual types, eliminating these costs and making the code both safer and faster. List List<T> is a generic collection that dynamically stores elements of a specific type. T specifies the type of elements the list will contain. using System ; using System.Collections.Generic ; var numbers = new List < int >(); numbers . Add ( 10 ); numbers . Add ( 20 ); numbers . Add ( 30 ); foreach ( int n in numbers ) Console . WriteLine ( n ); // Output: // 10 // 20 // 30 Note: Unlike arrays, List<T> can grow and shrink dynamically. Dictionary Dictionary is a generic key–value collection. TKey specifies the type of the key, and TValue specifies the type of the value. using System ; using System.Collections.Generic ; var students = new Dictionary < int , string >(); students [ 101 ] = "John" ; students [ 102 ] = "Mary" ; students [ 103 ] = "Michael" ; foreach ( var kv in students ) Console . WriteLine ( $" { kv . Key } → { kv . Value } " ); // Output: // 101 → John // 102 → Mary // 103 → Michael Note: Each Key in a dictionary must be unique. Attempting to add the same key again will cause an error. Creating Your Own Generic Classes You can also define your own generic types, not just use built-in collections. This allows you