Generic in C# – Basic Practice Example

Generic is a feature of C# programming language, which helps us save a lot of repeating works in our journey. It is efficient and widely used in practice.

Background

Imaging, we need to add many items into a list; and these items might be String, Integer, etc. Without Generic, we need to write at least one function for each data type; this work can be repeated and boring.
With the benefit of Generic, we need to write the function once, instead of writing them all.

Example – add string items to a list

public class MyString
     {
         private List myStringList = new List();
         public void AddString(String item)     
         {         
             myStringList.Add(item);     
         }     
         public String GetStringAt(int i)     
         {         
             return myStringList[i];     
         } 

}

Example – add int items to a list

public class MyInteger 
{     
      private List<int> myIntList = new List<int>();     
      public void AddInt(int item)     
      {         
        myIntList.Add(item);     
      }     
      public int GetIntAt(int i)     
     {         
        return myIntList[i];     
     } 
}

As I mentioned before, we have to make an individual function for a different data type. There are many types out there, and they are countless types made by other developers. It is not realistic to write a specific function for any new type, which will cost a lot of time and money.

Generic can be the solution for this tricky situation. We don’t have to decide the data type initially, and we need to determine data type in runtime.

public class MyList<T>
     {
         private List<T> myList = new List<T>();
         public void addItem(T item)     
         {     
             myList.Add(item);     
         }     
         public T GetItemAt(int i)     
         {         
             return myList[i];     
         } 
}

As you can see, we replace the data type with a T in the above code. You don’t have to use T to represent a data type; you can use any other letters or words you are comfortable with.

Most importantly, we don’t know the data type at this stage; we determine the data type in run time. Here is an example.

class Program
     {
         static void Main(string[] args)
         {
             var stringList = new MyList<string>();
             stringList.addItem("Apple");
     } }

As you can see, we decide the List is holding a group of string items in runtime.


Leave a Reply

Your email address will not be published. Required fields are marked *