C#
Collections
Use List, Dictionary, HashSet, Queue, Stack, and read-only views.
By EZ4Code Team
collectionslistdictionary
Code
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
// List - ordered, indexable
var list = new List<int> { 3, 1, 2 };
list.Add(4);
list.Sort();
Console.WriteLine(string.Join(",", list)); // 1,2,3,4
// Dictionary - key/value
var dict = new Dictionary<string, int>();
dict["a"] = 1;
dict.TryGetValue("b", out int v);
Console.WriteLine($"has b? {dict.ContainsKey("b")}");
// HashSet - unique elements
var set = new HashSet<int> { 1, 2, 2, 3 };
set.Add(2);
Console.WriteLine($"set count = {set.Count}"); // 3
// Queue and Stack
var q = new Queue<string>();
q.Enqueue("a"); q.Enqueue("b");
Console.WriteLine(q.Dequeue());
var stack = new Stack<int>();
stack.Push(1); stack.Push(2);
Console.WriteLine(stack.Pop());
// Read-only wrapper
var ro = new ReadOnlyCollection<int>(list);
Console.WriteLine(ro[0]);Explanation
List<T> is a growable array, Dictionary<TKey,TValue> maps keys to values, and HashSet<T> enforces uniqueness with O(1) lookups. Queue<T> and Stack<T> provide FIFO and LIFO semantics respectively. ReadOnlyCollection<T> wraps a list so external callers can read but not mutate it.
More C# Snippets
LINQ Query
Filter, project, sort, group, and aggregate sequences with LINQ.
Async and Await
Run I/O concurrently with async methods, await, and Task.WhenAll.
Properties
Encapsulate state with auto, computed, validated, and init-only properties.
Generics
Write type-parameterized methods and classes with constraints.
Delegates and Events
Define delegate types and publish events with safe subscription.
Reflection
Inspect type metadata and invoke members at runtime via System.Reflection.