C# Generics Programming

In this chapter you will learn
  • What are Generics
  • How to Write Generics Program in C#
  • Benefit of Generics in C#

What are Generics

In simple words, Generics are that type of classes which has PlaceHolder instead of datatypes. When you create generic classes you don’t specify its data type; datatypes are defined when you create objects. This makes Generic classes reusable and type-safe and your Generic classes and methods are able to work with any datatypes.

More about Generics

  1. Generics improves code usability, type safety and performance.
  2. Mostly Generics are used for creating collection classes.
  3. You can use Generics by adding System.Collections.Generic namespace.
  4. You can create your own Generic interfaces, classes, methods, events and delegates.

Declare Generics Class

public class GenericList<T>
    {
        void Add(T input) { }
    }

Use Generics in Programming

class TestGenericList
    {
        private class ExampleClass { }
        static void Main()
        {
            // Declare a list of type int.
            GenericList<int> list1 = new GenericList<int>();

            // Declare a list of type string.
            GenericList<string> list2 = new GenericList<string>();

            // Declare a list of type ExampleClass.
            GenericList<ExampleClass> list3 = new GenericList<ExampleClass>();
        }
    }

Programming Example

using System;
using System.Collections.Generic;

namespace Generics_Example
{
    //Declare Generics 
    public class GenClass<T>
    {        
        public void GenFunction(T printvalue)
        {
            Console.WriteLine(printvalue);
        }
    }
    public class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Printing Integer Value");
            GenClass<int> gen=new GenClass<int>();
            gen.GenFunction(144);

            Console.WriteLine("Printing String Value");
            GenClass<string> genstring=new GenClass<string>();
            genstring.GenFunction("Hello String");
        }
    }
}

Output

Printing Integer Value
144
Printing String Value
Hello String
_

Here, I have written the very simple program and hope you will understand it very easily. In the above program, I have created a Generic class GenClass which has a placeholder. This class also has a method GetFunction that accepts a T type parameter and prints on the console. is a placeholder that is replaced by datatype when created objects.

Summary

In this chapter, you learned What are Generics in C# Programming, Its benefit, and complete programming example.

 

Share your thought