Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explain Generics in layman style in C#? [duplicate]

Tags:

c#

generics

Duplicate of What is the "< >" syntax within C#


Actually i want to know 'why and when should i use generics?'.

What is the need for it?

like image 210
Dhanapal Avatar asked Feb 28 '23 21:02

Dhanapal


1 Answers

Generics are a way of ensuring Type Safety at Compile time in C#.

Example- Pre-Generics:

class Person 
{
 string name;
 string lastname;
 public Person(string _name )  { this.name = _name; }
}

class ClientCode
{
   public static void Main()
   {
         //create a list of person
         ArrayList personList = new ArrayList();
         Person p1 = new Person("John");
         Person p2 = new Person("Ram");
         personList.Add(p1);
         personList.Add(p2);
         // BUT, someone can do something like:
         // ArrayList does not stop adding another type of object into it
         object q = new object();
         personList.Add(q);
         // while accessing personlist
         foreach(object obj in personlist)
         {
            Person p = obj as Person;
            // do something, for person
            // But it will fail for last item in list 'q' since its is not person.
         }
   }
}

Example- Post-Generics:

class ClientCode
{
   public static void Main()
   {
         //create a list of person
         List<Person> personList = new List<Person>();
         Person p1 = new Person("John");
         Person p2 = new Person("Ram");
         personList.Add(p1);
         personList.Add(p2);
         // Someone can not add any other object then Person into personlist
         object q = new object();
         personList.Add(q); // Compile Error.
         // while accessing personlist, No NEED for TYPE Casting
         foreach(Person obj in personlist)
         {
            // do something, for person
         }
   }
}
like image 82
NileshChauhan Avatar answered Mar 10 '23 23:03

NileshChauhan