What is the difference between generic and non-generic collections in C#?
Generic collections are type-safe and defined using generics (<T>), allowing you to specify
the type of elements they hold. This ensures compile-time type checking and eliminates the
need for casting.
Non-generic collections, on the other hand, store elements as objects (object type),
requiring boxing/unboxing for value types and casting for reference types.
Example:
// Generic collection
List<int> numbers = new List<int>();
numbers.Add(10); // No boxing, type-safe
// Non-generic collection
ArrayList list = new ArrayList();
list.Add(10); // Boxing occurs
int value = (int)list[0]; // Needs casting
Real-world use case:
In applications dealing with specific data types (e.g., a list of customer IDs), generic
collections are ideal. Non-generic collections may be used in legacy systems or when
dealing with multiple data types.