Skip to main content

Command Palette

Search for a command to run...

My basic understanding of C# generics

Published
2 min read
My basic understanding of C# generics
R

I am a recent graduate at the beginning of my software development career. I enjoy documenting my learnings through my blogs

Generic means a characteristic of or relating to a class or group of things; not specific, common, or general (Oxford Languages). In terms of C#, generic means not specific to a distinct data type.

Think of generics as a lunchbox, your lunchbox can hold different foods at different times. Meaning, your lunchbox is the class and the foods are the data types. This can be described as having a flexible container that can hold different data types, like strings, ints or even a custom type.

A generic class is written similar to the example below:

public class Lunchbox<T>
{
    ...
}

You would then build this class up with its properties, constructors and methods:

public class Lunchbox<T>
{
    // Properties
    private T lunchItem;

    // Constructors
    public Lunchbox(T newlunchItem)
    {
        lunchItem = newlunchItem;
    }

    // Methods
    public T GetLunchItem
    {
        return lunchItem
    }
}

Then in your main program, you would create a collection to store these various lunchbox foods:

class Program
{
    static void Main()
    {
        // Create a Lunchbox for sandwiches (string)
        Lunchbox<string> sandwichLunchbox = new Lunchbox<string>("BLT", "Chicken and Stuffing", "Ham and Cheese");

        // Get the items from the lunchbox
        string sandwich = sandwichLunchbox.GetLunchItem();

        // Display the items from the lunchbox
        Console.WriteLine("Sandwich: " + sandwich);
    }
}

Why use generics?

Reusability: It is reusable because you don't need a different class for each data type, the generic class allows for different inputs.

Safety: When you specify the data type you intend to use, you can only use this type of input. If you define a string for example, but input an int, a compile-time error will occur because it expects the defined type of string.

Flexibility: Generics are very flexible because they can adapt to various data types, even custom types.

References