C# Generic

Generic in C#

Quick Links


C# Generic allow the reuse of code across different types.

Generic is a concept that allows us to define classes and methods with placeholder. C# compiler replaces these placeholders with specified type at compile time. The concept of generics is used to create general purpose classes and methods.

o define generic class, we must use angle <> brackets. The angle brackets are used to declare a class or method as generic type.


Example:

using System;
namespace CSharpProgram
{
    class GenericClass<T>
    {
        public GenericClass(T msg)
        {
            Console.WriteLine(msg);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            GenericClass<string> gen   = new GenericClass<string> ("This is generic class");
            GenericClass<int>    genI  = new GenericClass<int>(101);
            GenericClass<char>   getCh = new GenericClass<char>('I');
        }
    }
}

C# Generic Classes:

Generic types can also be used with classes.

The most common use for generic classes is with collections of items, where operations such as adding and removing items from the collection are performed in basically the same way regardless of the type of data being stored. One type of collection is called a stack. Items are “pushed”, or added to the collection, and “popped”, or removed from the collection. A stack is sometimes called a Last In First Out (LIFO) data structure.

Example :

class Stack<T> {
  int index=0;
  T[] innerArray = new T[100];
  public void Push(T item) {
    innerArray[index++] = item; 
  }
  public T Pop() {
    return innerArray[--index]; 
  }
  public T Get(int k) { return innerArray[k]; }
}

Generic Method Example


using System;
namespace CSharpProgram
{
    class GenericClass
    {
        public void Show<T>(T msg)
        {
            Console.WriteLine(msg);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            GenericClass genC = new GenericClass();
            genC.Show("This is generic method");
            genC.Show(101);
            genC.Show('I');
        }
    }
}

Recommended Posts:

Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *