Generics in C#

In this article, we ae going to explain about Generics in C#. Generic means the general form, not anything specific. In C#, generic means not specific to any particular data type.

The concept of generics is used to create general-purpose classes and method. It is not specific to any particular data type, but type is decided by the compiler at the time of compilation.

Let’s discuss using example, by using a generic “type” parameter T, you can write a single class that can be used by client code without any risk of runtime casts. Example is shown below.

Generic Method Example

public class CustomerList<T>
    {
        public void Show<T>(T input)
        {
            Console.WriteLine(input);
        }
    } 

public  class Program
    {
        static void Main(string[] args)
        {
            // Declare a list of type = int.
            CustomerList<int> list1 = new CustomerList<int>();
            list1.Show(101);
            list1.Show(102);


            // Declare a list of type = string.
            CustomerList<string> list2 = new CustomerList<string>();
            list2.Show("Rakesh");
            list2.Show("Mukesh");


            Console.Read();
        }
    }

How can we identify that our class or method is generic. If at the end of class name or method name, you observe angular braces <T> which indicates these are generic and can accept any data type or class in it.

Generics in C#

In above example we have created list of type int and string too and both will get printed in console. We can also pass class to our generic method as shown below. Hence, we can say that generic method is generalized and can accept all data types and class too and without any overhead of boxing/ unboxing.

  • Class “CustomerList” is generic because it contains <T> after its name.
  • Methods “Show” is also generic because of <T> after its name.
  • Next we’ll pass new EmpClass into our show methods which is generic.
  • In our example it is <T> but it can anything like <P> or anything else.     

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Generics
{
    // Declare the generic class with type T.
    public class CustomerList<T>
    {
        public void Show<T>(T input)
        {
            Console.WriteLine(input);
        }
    }
    public  class Program
    {
        static void Main(string[] args)
        {
            // Declare a list of type int.
            CustomerList<int> list1 = new CustomerList<int>();
            list1.Show(101);
            list1.Show(102);


            // Declare a list of type string.
            CustomerList<string> list2 = new CustomerList<string>();
            list2.Show("Rakesh");
            list2.Show("Mukesh");

            // Declare a list of type EmpClass.
            CustomerList<EmpClass> list3 = new CustomerList<EmpClass>();
            EmpClass obj = new EmpClass();
            obj.CustomerID = 101;
            obj.BankNumber = 1;
            obj.customerFirstName = "John";
            obj.customerLastName = "Smith";
            list3.Show(obj);

            Console.Read();
        }
    }
 
    //private void show() { }
    public class EmpClass
    {
        private int _BankNumber, _CustomerID;
        private string _customerFirstName, _customerLastName;
        public int BankNumber { get { return _BankNumber; } set { _BankNumber = value; } }
        public int CustomerID { get { return _CustomerID; } set { _CustomerID = value; } }
        public string customerFirstName { get { return _customerFirstName; } set { _customerFirstName = value; } }
        public String customerLastName { get { return _customerLastName; } set { _customerLastName = value; } }
    }


}

See below, we have passed the “EmpClass” object to our generic “Show” method.

Generics in C#

Important points of Generics:

  • Generics was introduced in C# 2.0
  • Generic allow you to write a class that can work with any data type.
  • Generic types are used to maximize code reusability.
  • Generics are faster because it does not perform boxing and unboxing.
  • Generics are basically used to create collection classes.
  • Generics avoid the cost of casting and ensure type safety and also enhance performance.
  • Generic data type can be found in”System.Collections.Generic” namespace and one must prefer this instead of “ArrayList”.
  • Generic class or methods can be defined using angular brackets <T>, where T is type whose data type is decided at runtime.

Why do we need generics in C#?

As name indicates generics provide us the flexibility to pass any data type or class it. In general, we defined the input parameters either int or string and that method accept int and string only, but with generic make it easy to pass anything as you want. In above example same “Show” method accept int, string and class objects too. We can use generics in method, class, structure and in interface too. Generic allow us to use stronger type-checking and elimination of boxing/ unboxing.

What are the disadvantages of generics in C#?  

  • Dynamic methods cannot be generic.
  • Enumerations cannot have generic type parameters.
  • Nested type can never be instantiated.

Do generics increase performance C#?

Yes, in case of generic overhead of casts and boxing/ unboxing do not take place. Additionally, it a common generalize method instead of multiple so there will be a smaller number of lines of code which compiler need to compile so using above point we can say that generics increase performance.

Is generics runtime or compile time?

Regarding type-correctness generics are checked at compile-time. If you ‘ll pass wrong data type, then blue line will appear under your method which indicates compile time error.     

When should you use generics?

You can use it to increase your code reusability and enhance the performance. The most common use of generics in C# is to create collection classes.

Do generics exist after compilation?

Yes, same generics stays in the compiled class created by the GIT complier. In IL code generic definition of a class or a method can be seen.

Can we pass null in generic method?

No, it will give error, please check below code. ‘Show’ is our generic method and we have made a call to this and passed null in it (please check code in highlighted green box).

Generics in C#

Can we use generics with array?

No, if we have generic type objects and we want to create its array then it will give compile time error. Hence it is not feasible.

What are the benefits of generics in C#?  

  • It provides code reusability.
  • There is no need for casting. This overhead can be saved.
  • It is faster.
  • No boxing and unboxing happen in generics.
  • We can create generic for interface, classes, method, events and delegate too.

How to use generic class in C#?

Please check out below sample code.

// Below is generic class and generic method

public class CustomerList<T>
    {
        public void Show<T>(T input)
        {
            Console.WriteLine(input);
        }
    } 

 // Going to use above generic method in below code.
            CustomerList<int> list1 = new CustomerList<int>();
            list1.Show(101);
            list1.Show(102);

We hope above explanation of generic have cleared your doubts regarding use of generics and I believe you’ll use generic in your daily development practices. For more information you can check out Microsoft learn.

For more information you can visit our C# Section for more such articles.

Leave a Reply

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