Generic Methods in C#

Generic allows any data type of elements in a Class or Method. That means generic class, and generic method works with any type of element. In this article, we discuss how to create a generic class and generic method in C#. 

Open Microsoft Visual Studio 2015 => Create a new console application and name it as CSharpGenericExample and below code.  

using System;

namespace CSharpGenericExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Employee<int> obj1 = new Employee<int>(100);
            Console.WriteLine(obj1.GetEmpDetails());  

            Employee<string> obj2 = new Employee<string>("Raj");
            Console.WriteLine(obj2.GetEmpDetails());  

            Console.ReadLine();
         }
    } 

    public class Employee<T>
    {
        T _empRecord;

        public Employee(T t)
        {
            // The field has the same type as the parameter.
            this._empRecord = t;
        } 

        public string GetEmpDetails()
        {
            string sEmpInfo = string.Empty;

            if (_empRecord.GetType() == typeof(Int32))
            {
                sEmpInfo = "The name of the employe is Raj for the Employee Id " + _empRecord.ToString();
            }
            else if (_empRecord.GetType() == typeof(string))
            {
                sEmpInfo = "The id of the employe is 100 for the Employee name " + _empRecord.ToString();
            }
            else
            {
                sEmpInfo = "";
            } 

            return sEmpInfo;
        }
    }
}

As shown above, we have written Employee class and GetEmpDetails() method with substitute parameter T. When the compiler compels the code it replaces the substitute with the appropriate data type. In the above example we passed integer data type to Employee class constructor first time, and in the second object, we have passed the string data. Run the application, and it displays output as below.