What are generics in C# using an example?

 

What are Generics

Generics in C# allows us to create classes and methods with the type as the parameter (which are type-safe).They allow us the designing of classes and methods with type parameters and whose types are specified only at the time of instantiation. When these types are instantiated CLR compiles at compile time and stores information related to the generic types.

Generics are different from generic collections.Generic collections are emerged from generic concept. It helps us to maximize code reuse, performance and type safety.

Generics are strongly type collections.

Generics helps to decouple the data-type from the logical code snippet which makes the code to reuse again and again.

We can also create classes and pass to it the generic parameter as type.

We can use generics in our code by calling the namespace "using System.Collections.Generic;".

Micorsoft applied generic concept on

  • .NET collections to make generic collections.
  • Arraylist to make list generic collections.
  • Hashtables to make Dictionary.
  • Stacks and Queues to make Stacks and Queues generics.

Syntax

 
    public class GenericsClass
    {
         ......
    }

Where is a generic parameter, we can pass any data type to this parameter.

Generics in c# example

 

  usign System;
  using System.Collections.Generic;

    public class GenericsClass
    {
        private T a;
        privateT b;

        public GenericsClass(T x, T y)
        {
            a = x;
            b = y;
        }

        public bool CompareResult()
        {
            if (a.Equals(b))
            {
                return true;
            }
            else
            {

                return false;
            }
        }
    }


    class Program
    {
        static void Main(string[] args)
        {

            GenericsClass obj1 = new GenericsClass("Khadak", "Khadak");
            Console.WriteLine("Compare Result obj1 --> {0}", obj1.CompareResult());

            GenericsClass obj2 = new GenericsClass("Khadak", "Shaam");
            Console.WriteLine("Compare Result obj2 --> {0}", obj2.CompareResult());


            GenericsClass objInt1 = new GenericsClass(1, 1);
            Console.WriteLine("Compare Result objInt1 --> {0}", objInt1.CompareResult());

            GenericsClass objInt2 = new GenericsClass(1, 8);
            Console.WriteLine("Compare Result objInt2 --> {0}", objInt2.CompareResult());


            GenericsClass objChar1 = new GenericsClass((char)(97), (char)(97));
            Console.WriteLine("Compare Result objChar1 --> {0}", objChar1.CompareResult());


            GenericsClass objChar2 = new GenericsClass((char)(97), (char)(98));
            Console.WriteLine("Compare Result objChar2 --> {0}", objChar2.CompareResult());

            GenericsClass objDouble1 = new GenericsClass(1.1, 1.1);
            Console.WriteLine("Compare Result objDouble1 --> {0}", objDouble1.CompareResult());


            GenericsClass objDouble2 = new GenericsClass(1.1, 1.2);
            Console.WriteLine("Compare Result objDouble2 --> {0}", objDouble2.CompareResult());
            
        }
    }

About The Code

In this example of code, I have separated the data-type from the class code and data-type will be decided on compile time. Class code is flexible that we can pass any data-type and at a same time will maintain type-safety and performance.

As you see from above the code that we have created a custom generic class called "GenericsClass" with generic parameter "" and a constructor which takes the two input values (Datatype of those values will be decided on compile time) and assign it to private variables.

Now in the next step we have created boolean method "CompareResult()" which compares the both variables are equal or not according to that it returns the result.

Kindly note "T" in "GenericsClass" is a generic parameter.

In the final step, I have just created the objects of "GenericsClass" in the main "Console Application Program" and replaced the generic parameter with the data-type.

As you see class "GenericsClass" is so flexible that we can attach any data-type and automatically it will function according to that data-type and with maintaining the type-safety and performance.

Output


When To Use

Generics helps to separate the data-type from the logical code i.e. from methods and classes. So if you want to maximize your code resuability and maintain its type safety, and performance then use generics.

Generics acts as a bridge between dot.net data-types and your custom logical code and provides flexibility to maximize the code resuability and reduces code.

For more information you can visit : http://msdn.microsoft.com/en-us/library/ms379564(v=vs.80).aspx.

Hey Friends, Feel free to add your valuable comments and if you like this article kindly share it with your friends. In the upcoming article we will be covering Generic Collections.Thank You...!

 

 

:: SHARE THIS POST ::

        
 

More C# Articles To Read Next:

 
Aug
25
2013

Use of string.Format method in C# with an example?

CLICK TO READ FULL ARTICLE

Views - 25642 |Category - C#

Jul
31
2013

What is mixed mode arithmetic expression with an example?

CLICK TO READ FULL ARTICLE

Views - 21354 |Category - C#

Jul
22
2013

What is an event handler and explain how it is designed ?

CLICK TO READ FULL ARTICLE

Views - 6285 |Category - C#

Jul
20
2013

Is C# is Modern, Type Safe, Versionable and Inter operability Language ?

CLICK TO READ FULL ARTICLE

Views - 9916 |Category - C#

Jul
09
2013

Discuss Boxing and Unboxing in the context of value types and reference types

CLICK TO READ FULL ARTICLE

Views - 7401 |Category - C#

 
Author: Gurunatha Dogi
is a software engineer by profession and founder of Onlinebuff.com, Onlinebuff is a tech blog which covers topics on .NET Fundamentals, Csharp, Asp.Net, PHP, MYSQL, SQL Server, Cell Phones and lots more. Follow me @ and twitter.
Leave a Comment......

All fields marked with * are mandatory

gok1c

 

 
Comments

Posted by Vishal on 2016-04-29

Very Simple and nice Explaination. Keep shairing. Thank you sir

Posted by Kiran on 2014-06-22

Really great article

Posted by Satish on 2014-06-16

HI Nice Article helps very much...keep going on

Posted by Satish on 2014-05-30

Very good. it's helped me a lot as a fresher

Posted by Rakesh on 2014-04-17

program shows error: Inconsistent accessibility on constructor