Generics are a programming language feature that allow you to define classes, methods, interfaces, or functions with placeholders for types, so they can work with any data type while still maintaining type safety.
Generics in C# allow to create type-safe, reusable code by defining classes, methods, and interfaces with type parameters. This means we can write code that works with any data type without sacrificing performance or safety.
Why Use Generics?
Type Safety: Prevents runtime errors by enforcing type constraints at compile time.
Code Reusability: Eliminates the need to write duplicate code for different data types.
Performance: Reduces unnecessary type conversions (boxing/unboxing).
//=========================================================================
In C#, collections are classes that store groups of related objects. They provide flexible ways to manage data—like adding, removing, searching, and sorting—without needing to know the size or type of data at compile time.
Non-Generic Collections (System.Collections)
Examples:
ArrayList Resizable array of objects;Stores elements as object , requiring casting/unboxing for value types.
Hashtable maps keys to values using a technique called hashing.
SortedList Key/value pairs sorted by keys.
BitArray Collection of bits represented as; Useful for compact storage and bitwise operations.
Generic Collections (System.Collections.Generic)
Type-safe and more efficient Introduced in .NET 2.0
Examples:
List – dynamic array
Dictionary – key-value pairs
Queue – FIFO
Stack – LIFO
HashSet – unique elements
LinkedList – doubly linked list
in C#, an array is considered a collection, but with some distinctions.
✅ How Arrays Fit In
Arrays are part of the System.Array class, which implements IEnumerable and IEnumerable<T>, making them compatible with LINQ and foreach loops.
They are fixed in size and strongly typed, meaning once created, their length and element type cannot change.
//=====================================================================================================