Generics in C#

In c#, generic is a type which is used to define a class, structure, interface or method with a placeholders (type parameters) to indicate that they can store or use one or more of the types. In c#, the compiler will replace a placeholders with the specified type at compile time.

 

In c#, mostly we will use a generics with collections and the methods that operate on them to specify a type of objects to be stored in a collection. The generics are introduced in .NET Framework 2.0 with a new namespace called System.Collections.Generic

 

In c#, generics are useful to improve the code reusability, type safety and the performance when compared with the non-generic types such as arraylist.

C# Generics Declaration

To define a class or method as generic, then we need to use a type parameter as a placeholder with an angle (<>) brackets.

 

Following is the example of defining a generic class with type parameter (T) as placeholder with an angle (<>) brackets.

 

public class GenericClass<T>

{

    public T msg;

    public void genericMethod(T name, T location)

    {

        Console.WriteLine("{0}", msg);

        Console.WriteLine("Name: {0}", name);

        Console.WriteLine("Location: {0}", location);

    }

}

If you observe above class, we created a class (GenericClass) with one parameter (msg) and method (genericMethod) using type parameter (T) as placeholder with an angle (<>) brackets.

 

Here, the angle (<>) brackets will indicate a GenericClass is generic and type parameter (T) is used to accept a requested type. The type parameter name can be anything like X or U or etc. based on our requirements.

 

Generally, while creating an instance of class we need to specify an actual type, then the compiler will replace all the type parameters such as T or U or X, etc. with specified actual type. In c#, following is the example of creating an instance of generic class.

 

// Instantiate Generic Class, string is the type argument

GenericClass<string> gclass = new GenericClass<string>();

gclass.msg = "Welcome to Tutlane";

gclass.genericMethod("Suresh Dasari", "Hyderabad");

If you observe above code, we are sending a type as “string” so the compiler will substitute all the type parameters (T) with defined type “string” and our class (GenericClass) will be like as shown below.

 

public class GenericClass

{

    public string msg;

    public void genericMethod(string name, string location)

    {

        Console.WriteLine("{0}", msg);

        Console.WriteLine("Name: {0}", name);

        Console.WriteLine("Location: {0}", location);

    }

}

In c#, we can also create our own custom generic types and methods to provide our own generalized solutions that are type-safe and efficient.

C# Generic Class Example

Following is the example of creating a generic class using type parameter (T) with angle (<>) brackets in c# programming language.

 

using System;

namespace Tutlane

{

    public class GenericClass<T>

    {

        public T msg;

        public void genericMethod(T name, T location)

        {

            Console.WriteLine("{0}", msg);

            Console.WriteLine("Name: {0}", name);

            Console.WriteLine("Location: {0}", location);

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            Console.WriteLine("****Generics Example****");

            // Instantiate Generic Class, string is the type argument

            GenericClass<string> gclass = new GenericClass<string>();

            gclass.msg = "Welcome to Tutlane";

            gclass.genericMethod("Suresh Dasari", "Hyderabad");

            Console.ReadLine();

        }

    }

}

When we execute above c# program, we will get the result like as shown below.

 

C# Generic Class Example Result

 

This is how we can use generics in c# to create a generic classes or methods based on our requirements.

C# Generic Class as Base / Derived Class

In c#, we can use generic class as base class, but we need to provide a type instead of type parameter for the base class because there is no way to send a required type argument to instantiate a base class at run time.

 

Following is the example of using a generic class as base class in c# programming language.

 

// No Error

class DClass1 : GenericClass<string> {

// implementation

}

// Compile Time Error

//class DClass2 : GenericClass<T> {

// implementation

//}

In case, if derived class is generic, then we don’t need to specify a type for generic base class instead we can use type parameter (T).

 

Following is the example of defining a generic derived class in c# programming language.

 

// No Error

class DClass1 : GenericClass<string> {

// implementation

}

// No Error

class DClass2<T> : GenericClass<T>{

// implementation

}

C# Generic Methods

In c#, if we define a method with type parameter, then it is called a generic method. Following is the example of defining a generic method with type parameter using angle (<>) brackets.

 

public void genericMethod<T>(T a, T b)

{

     // Implementation

}

This generic method can be called either by specifying the type of argument or without an argument like as shown below.

 

genericMethod<int>(1, 2);

 

//or

 

genericMethod(1, 2);

C# Generic Method Example

In c#, we can call a generic method by passing any type of arguments. Following is the example of defining a generic method in c# programming language.

 

using System;

namespace Tutlane

{

    public class SampleClass

    {

        public void GMethod<T>(T a, T b)

        {

            Console.WriteLine("Param1: {0}", a);

            Console.WriteLine("Param2: {0}", b);

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            Console.WriteLine("****Generics Method Example****");

            SampleClass s = new SampleClass();

            s.GMethod<int>(1, 2);

            s.GMethod("Suresh Dasari", "Hyderabad");

            Console.ReadLine();

        }

    }

}

If you observe above code, we are calling our generic method (GMethod) with or without type parameter and sending a different type of arguments based on our requirements.

 

When we execute above c# program, we will get the result like as shown below.

 

C# Generic Method Example Result

 

This is how we can define a generic methods in c# programming language based on our requirements.

C# Generic Delegates

In c#, a generic delegate will be same like normal delegate but only difference is a generic delegate will have a generic type with angle (<>) brackets.

 

Following is the example of defining a generic delegate in c# programming language.

 

using System;

 

namespace Tutlane

{

    // Declare Generic Delegate

    public delegate T SampleDelegate<T>(T a, T b);

    class MathOperations

    {

        public int Add(int a, int b)

        {

            return a + b;

        }

        public int Subtract(int x, int y)

        {

            return x - y;

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            Console.WriteLine("****Generic Delegate Example****");

            MathOperations m = new MathOperations();

            // Instantiate delegate with add method

            SampleDelegate<int> dlgt = new SampleDelegate<int>(m.Add);

            Console.WriteLine("Addition Result: " + dlgt(10, 90));

            // Instantiate delegate with subtract method

            dlgt = m.Subtract;

            Console.WriteLine("Subtraction Result: " + dlgt(10, 90));

            Console.ReadLine();

        }

    }

}

If you observe above code, we defined a delegate (SampleDelegate) with generic type parameter (T) using angle (<>) brackets and accessing it by creating an instance of delegate with required argument (int).

 

When we execute above c# program, we will get a result like as shown below.

 

C# Generic Delegate Example Result

 

This is how we can use generics with delegates based on our requirements in c# programming language.

C# Generics Overview

Following are the important properties of generics in c# programming language.

 

  • In c#, generics are represented by using angle bracket <>.
  • To define a class or method as generic, then we need to use a type parameter as a placeholder with an angle (<>) brackets.
  • The compiler will replace all the placeholders with the specified type at compile time.
  • In c#, generics are useful to improve the code reusability, type safety and the performance when compared with the non-generic types such as arraylist.
  • In c#, we can use a generics with interfacesclassesmethods, propertiesdelegates, events and with operators.