generic classes and methods in c#

generic classes and methods in c#

Generic is a type parameter technique. Using this technique we write a class, or methods that can work any data type that means user defines data type or system define data type. It is type-safe.

using System.Collections.Generic;

Example of Generic Type

  namespace Generics
    public class GeneRicType
        public T _value;
        public GeneRicType(T t)
            this._value = t;

        public void Input()

    public class Program
        static void Main(string(] args)
            // Integer type
            GeneRicType obj = new GeneRicTypecint>(120);

            // string type
            GeneRicTypecstring> obj1 = new GeneRicTypecstring>("Hi, -
 The OutPut as given below.
    Hi, Dear!!

Example for Sum of Two Number using Generic Type

In this example, both class and methods are generic type, here we decide the output at the run-time what type we want that means Int, float etc.

namespace Generics
    public class CalculationClass
        public T _valuel;
        public T _value2;
        public CalculationClass(T tl, T t2)
            this._valuel = tl;
            this._value2 = t2;
        public T InputValues objInt = new CalculationClass(Convert.ToInt32(Console.ReadLine()),
        Console.WriteLine("Sum Of Two : "+ objInt.InputValues());
        CalculationClass objDoble = new CalculationClass(Convert.ToDouble(Console.ReadLine()),
        Console.WriteLine("Sum Of Two : " + objDoble.InputValues());

The Output as given below.

Sum Of Two : 30

Sum Of Two :  30.4

Remark on Generic Type
  1. We use generic types to maximize the code reuse, increase the performance of a application and type safety. 
  2. Most common use of generics is to create collection classes just like ArrayList, Dictionary, Stack, Queue etc.


Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
My Blogs - and
My Books - Google Amazon and Flipkart Book Store!

You Might Also Like
Post a Comment Powered by Blogger.
ASK Questions
SQL Server NodeJs TypeScript JavaScript Angular SQL Server My Book