Skip to main content

Generics in C#

Generics Explained in C#

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

 Mostly we use 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

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

 Generics Declaration in C#

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

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

     public class GenericClassExample<T>

    {

        public T message;

        public void GenericMethod(T name, T location)

        {

            Console.WriteLine($"{message}");

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

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

        }

    }

From the above class, we created a class (GenericClassExample) with one parameter (message) and method (GenericMethod) using type parameter (T) as placeholder with an angle (<>) brackets.

 

Here, the angle (<>) brackets will indicate a GenericClassExample 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 needs.

 

Generally, while creating an instance of the 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.


Generic Class Example in C#

The following is an example of creating a generic class using type parameter (T) with angle (<>) brackets in C#.

 

using System;

namespace CsharpnaijaTutorial

{

    public class GenericClassExample<T>

    {

        public T message;

        public void GenericMethod(T name, T location)

        {

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

            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

            GenericClassExample<string> genericclass = new GenericClassExample<string>

            {

                message = "Welcome to Csharpnaija"

            };

            genericclass.GenericMethod("Musa Gadabs", "Abuja");

            Console.ReadLine();

        }

    }

}

 

C# Generic Class as Base / Derived Class

In C#, you can use the generic class as a 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 a base class in C# programming language.


// Correct way of using Generic class without Error

class DClass1 : GenericClassExample<string>

{

    // implementation

}

 

// Compile Time Error

//class DClass2 : GenericClassExample<T> {

// implementation

//}

 

C# Generic Methods

In C#, if we define a method with type parameter, then it is called a generic method. The example code shows how to define 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 as shown below.

 

GenericMethod<int>(1, 2);

//or

GenericMethod(1, 2);

 

C# Generic Method Example

In C#, you can call a generic method by passing any type of arguments. The following is an example of defining a generic method in C# programming language.

 

using System;

namespace CsharpnaijaTutorial

{

    public class SampleClass

    {

        public void GenericMethod<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 sample = new SampleClass();

            sample.GenericMethod<int>(1, 2);

            sample.GenericMethod("Musa Gadabs", "Abuja");

            Console.ReadLine();

        }

    }

}

 

C# Generic Delegates

A generic delegate will be same as a normal delegate but the only difference is a generic delegate   will have a generic type with angle (<>) brackets.

 

The following is an example of defining a generic delegate in C#.

 

using System;

namespace CsharpnaijaTutorial

{

    // 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 mathOps = new MathOperations();

            // Instantiate delegate with add method

            SampleDelegate<int> delegat = new SampleDelegate<int>(mathOps.Add);

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

            // Instantiate delegate with subtract method

            delegat = mathOps.Subtract;

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

            Console.ReadLine();

 

        }

    }

}

 

Thank you

 

References

 

1. Tutlane

2.  TutorialsTeacher

3.  MicrosoftDocumentation

Comments

Popular posts from this blog

The String.Join Method in C# Explained

The String.Join Method in C#   The string.Join concatenates the elements of a specified array or the members of a collection, using the specified separator between each element or member. Overloads of string.Join Method Description Join(Char, Object[]) Concatenates the string representations of an array of objects, using the specified separator between each member. Join(Char, String[]) Concatenates an array of strings, using the specified separator between each member. Join(String, IEnumerable<String>) Concatenates the members of a constructed IEnumerable<T> collection of type String, using the specified separator between each member. Join(String, Object[]) Concatenates the elements of an object array, using the specified separator between each element. Join(String, String[]) Concatenates all the elements of a string array, usi...

Most Popular Programming Languages in 2020

Most Popular Programming Languages in 2020 In this blog post, you will learn about the most popular programming languages in 2020 for creating the best web applications. Check its pros and cons. Analyzed by technostacks Not very long ago, just a few people were considered to be computer programmers, and the general public viewed them with awe. In this digital age that we are now living in, however, a large number of IT jobs need a solid grasp of one or more programming languages. Whether one wants to develop a mobile app or get a certification for having programming knowledge, or even to learn new skills, one needs to opt for the right programming language. Below mentioned eight most popular programming languages which are in demand for software development and web applications. This is the most used programming languages in 2019 and will be in 2020. For each, there is little information about the language, benefits and its complexity, as well as about its usage. One must...

HashTable in C# with Example

  HashTable in C# with Example Hashtable  is used to store a collection of key/value pairs of different  data types  and are organized based on the hash code of the key.   Generally, the hashtable object will contain buckets to store elements of the collection. The bucket here, is a virtual subgroup of elements within the hashtable and each bucket is associated with a hash code, which is generated based on the key of an element.   In C#, hashtable is same as a  dictionary  object but the only difference is that the  dictionary  object is used to store a key-value pair of same  data type  elements.   When compared with  dictionary  object, the hashtable will provide a lower performance because the hashtable elements are of object type so the boxing and unboxing process will occur when we are storing or retrieving values from the hashtable.   C# HashTable Declaration Hashtable is a non-generic type...