Generic Types

Learn about classes that accept type parameters.

Introduction

Consider the following Holder class:

public class Holder
{
    public string[] Items { get; private set; }

    public Holder(int holderSize)
    {
        Items = new string[holderSize];
    }

    public override string ToString()
    {
        string result = "Items inside: ";

        foreach (var item in Items)
        {
            result = result + item + " ";
        }

        return result;
    }
}

It has the Items property, which is string type. The Holder class holds string items. What if we need a similar class that holds integers? The functionality is the same, but the type is different.

We could suggest something like the following:

public class IntHolder
{
    // Now, the Items property holds integers
    public int[] Items { get; private set; }

    public IntHolder(int holderSize)
    {
        Items = new int[holderSize];
    }

    public override string ToString()
    {
        string result = "Items inside: ";

        foreach (var item in Items)
        {
            result = result + item + " ";
        }

        return result;
    }
}

This works. Is this feasible if we want to create such a class for many more types, though? We’d be copying the same code and changing the type of the internal array used to hold the items.

A better approach uses generics.

Generic types

Generics are classes with members whose types are specified during variable declaration and object creation. In other words, instead of having IntHolder or StringHolder, we can have a single class that instantiates as follows:

Holder<int> intHolder = new Holder<int>(); // Holder class holds integers
Holder<string> stringHolder = new Holder<string>(); // Holder class holds strings

With a generic Holder class, the type of the Items property is specified during variable declaration instead of being hard-coded inside the class:

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy