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
Hashtable
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, 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.
//=====================================================================================================