Generic Class in C#

In this article we will discuss about what is Generic Class in C# and how it will work in C#.
  • 3537

An Object will take string value or any value, the compiler will convert the value then the processing of Application will be slow because object will take object type values. This was the Drawback of the Non-Generic Classes. So, the Concept of Generic Classes was introduced in 2.0 version of C#. Through which we can create such kinds of classes, methods, interfaces which takes type as a parameter on which basis we want to work. These Generic Classes resides in System.Collections.Generic Namespace.

There is the program to swap two different kinds of values using Generic Class Concept:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Collections;

 

namespace ConsoleApplication13

{

    class Program

    {

        static void Main(string[] args)

        {

            st<string> obj = new st<string>();

            st<int> ob = new st<int>();

            obj.swap("megha", "meesha");

            ob.swap(10,20);

            Console.ReadLine();

 

        }

        public class st<p>

        {

            public void swap(p x, p y)

            {

                p temp;

                temp = x;

                x = y;

                y = temp;

                Console.WriteLine("X is :" + x + "  y is:" + y);

            }

        }

    }

}

 

Output:


image7.jpg

 

Here p stands for data type which we will pass when creating the object of the Class. Here we have passed string data type to the Class st so it will work on string data type and also we have passed the int data type then the class will work on the integer type data.

Ask Your Question 

Got a programming related question? You may want to post your question here

Programming Answers here

© 2020 DotNetHeaven. All rights reserved.