C# Collections and Generics
Ad
Generic Collections
C# generics let collections work with any type while staying type-safe. The main ones live in System.Collections.Generic.
List<T>
var names = new List<string> { "Sara", "Ali" };
names.Add("Omar");
names[0]; // "Sara"
Dictionary<K,V>
var ages = new Dictionary<string, int>();
ages["Sara"] = 25;
ages.TryGetValue("Sara", out int age); // safe lookup
HashSet<T>
var unique = new HashSet<int> { 1, 2, 2, 3 }; // {1,2,3}
Writing a Generic Method
T First<T>(List<T> items) => items[0];
int n = First(new List<int> { 1, 2 }); // type inferred
FAQs
List vs Array?
Arrays are fixed-size; List grows dynamically. Prefer List for most cases. More in our C# guides.
Why generics over object?
Type safety and no boxing/casting overhead.
