Why should we use generics?

For non-generic lists, we use collections from the universal base of the object type [https://docs.microsoft.com/en-us/dotnet/api/system.object], which is not type-safe at compile time. Let's assume that we are using a non-generic collection of ArrayList; see the following code snippet for more details:

ArrayList authorArrayList = new ArrayList {"Gaurav Aroraa", "43"}; 
foreach (string author in authorArrayList) 
{ 
    WriteLine($"Name:{author}"); 
} 

Here, we have an ArrayList with string values. Here, we have the age as a string which actually should be int. Let's take another ArrayList, which has the age as an int:

ArrayList editorArrayList = new ArrayList { "Vikas Tiwari", 25 }; foreach (int editor in editorArrayList) ...

Get Learn C# in 7 days now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.