Skip to content

#15 Generics

Not specifying a particular data type is called Generics. In C# we can define generic classes, interfaces, fields, methods, events, delegates, and operators using type parameter and without specific data type.

Type parameter is a placeholder for a particular type which is enclosed in angle brackets(<>).

they are mainly used to increase code reusability to add wrappers to the outputs. Even though they feel dynamic but they still are type-safe and compile-time errors are thrown in case of type issues. Also, they have a performance advantage because it removes the possibilities of boxing and unboxing.

using System;
using System.Text;

namespace Structures
    class Program
        static void Main(string[] args)
            //syntax to instantiating generic class when class is instantiated
            //T would be replaced by string.
            GenericIndexerclass<string> ptr = new GenericIndexerclass<string>();
   = "Hello World";

            GenericIndexerclass<string> cities = new GenericIndexerclass<string>();
            cities.AddOrUpdate(0, "Mumbai");
            cities.AddOrUpdate(1, "Chicago");
            cities.AddOrUpdate(2, "London");


    class GenericIndexerclass<T>
        //generic field
        public T data;
        public T[] arraydata = new T[10];

        //generic method
        public void AddOrUpdate(int index, T item)
            if (index >= 0 && index < 10)
                arraydata[index] = item;

        public T GetData(int index)
            if (index >= 0 && index < 10)
                return arraydata[index];
                return default(T);


Generic Constraints

This allows you to use constraints to restrict client code to specify certain types while instantiating generic types. It will give a compile-time error if you try to instantiate a generic type using a type that is not allowed by the specified constraints.

class DataStore<T> where T : class
    public T Data { get; set; }

DataStore<string> store = new DataStore<string>(); // valid
DataStore<MyClass> store = new DataStore<MyClass>(); // valid
DataStore<IMyInterface> store = new DataStore<IMyInterface>(); // valid
DataStore<IEnumerable> store = new DataStore<IMyInterface>(); // valid
DataStore<ArrayList> store = new DataStore<ArrayList>(); // valid
//DataStore<int> store = new DataStore<int>(); // compile-time error 

Published inC#

Be First to Comment

Leave a Reply

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