What are generics in C#?
Answer
Generics allow writing type-safe, reusable code where the type is a parameter. Instead of using object (which requires boxing and casting), generics maintain type safety at compile time. Syntax: public class Stack<T> { private List<T> items = new(); public void Push(T item) => items.Add(item); public T Pop() => items[^1]; }. Generic methods: public T Max<T>(T a, T b) where T : IComparable<T> => a.CompareTo(b) > 0 ? a : b;. Constraints: where T : class (reference type), where T : struct (value type), where T : new() (has parameterless constructor), where T : SomeBaseClass, where T : ISomeInterface. Built-in generic collections: List<T>, Dictionary<TKey,TValue>, Queue<T>, Stack<T>. Generics eliminate runtime casting errors and boxing overhead.
Previous
What is exception handling in C#?
Next
What is the difference between == and .Equals() in C#?