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

Collections in C#

Collections in C# In our previous article , we have learned about how we can use arrays in C#. Arrays in programming are used to group a set of related objects. So one could create an array or a set of Integers, which could be accessed via one variable name. What is Collections in C#? Collections are similar to Arrays, it provides a more flexible way of working with a group of objects. In arrays, you would have noticed that you need to define the number of elements in an array beforehand. This had to be done when the array was declared. But in a collection, you don't need to define the size of the collection beforehand. You can add elements or even remove elements from the collection at any point of time. This article will focus on how we can work with the different collections available in C#. There are three distinct collection types in C#: standard generic concurrent The standard collections are found under the System.Collections. They do not store elemen...

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...

System.IO Namesapce in C#

  System.IO Namesapce in C# A  file  is a collection of data stored in a disk with a specific name and a directory path. When a file is opened for reading or writing, it becomes a  stream . The stream is basically the sequence of bytes passing through the communication path. There are two main streams: the  input stream  and the  output stream . The  input stream  is used for reading data from file (read operation) and the  output stream  is used for writing into the file (write operation). From the above definition of file, the C# provides a namespace that enable us to manipulate file in C# called System.IO.   System.IO  is a  namespace  and it contains a standard IO (input/output) types such as classes , structures , enumerations , and  delegates  to perform a read/write operations on different sources like file, memory, network, etc.   System.IO Classes The table below shows differen...