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

Classes in C# Explained

C# Class Explained A class is nothing but an encapsulation of properties and methods that are used to represent a real-time entity, as explained by Guru99 . For instance, if you want to work with Guest’s data as in our previous DataDriven Web application . The properties of the Guest would be the Id, GuestName, Address, Phone number etc of the Guest. The methods would include the entry and modification of Guest data. All of these operations can be represented as a class in C# as shown below. using System; namespace CsharpnaijaClassTutorial {     public class Guest     {         public int Id { get ; set ; }         public string GuestName { get ; set ; }         public string Address { get ; set ; }         public string WhomToSee { get ; set ; }     ...

ASP.NET MVC Views

Views in ASP.NET MVC Application explained Find a related article By  Steve Smith  and  Luke Latham from Microsoft Corporation here In the Model-View-Controller (MVC) pattern, the  view  handles the application's data presentation and user interaction. A view is an HTML template with embedded  Razor markup . Razor markup is code that interacts with HTML markup to produce a webpage that's sent to the client. In ASP.NET MVC, views are  .cshtml  files that use the  C# programming language  in Razor markup. Usually, view files are grouped into folders named for each of the application's  controllers . The folders are stored in a  Views  folder at the root of the application as shown: The  Home  controller is represented by a  Home  folder inside the  Views  folder.  The  Home  folder contains the views for the  About ,  Contact , and  Index...

ASP.NET MVC Routing

ASP.NET MVC Routing ASP.NET MVC routing is a pattern matching system that is responsible for mapping incoming browser requests to specified MVC controller actions. When the ASP.NET MVC application launches then the application registers one or more patterns with the framework's route table to tell the routing engine what to do with any requests that matches those patterns. When the routing engine receives a request at runtime, it matches that request's URL against the URL patterns registered with it and gives the response according to a pattern match. Routing pattern is as follows A URL is requested from a browser, the URL is parsed (that is, break into controller and action), the parsed URL is compared to registered route pattern in the framework’s route table, if a route is found, its process and send response to the browser with the required response, otherwise, the HTTP 404 error is send to the browser. Route Properties ASP.NET MVC routes are res...