Search⌘ K
AI Features

Generic Types

Explore how to define and use generic types in C# to write adaptable and type-safe classes and methods. Understand the use of type parameters, default values for generics, and how to instantiate classes with different types. Gain the skills to avoid code duplication and handle multiple type parameters effectively.

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()
{
// Use string.Join to efficiently concatenate items
return "Items inside: " + string.Join(", ", Items);
}
}
A class designed specifically to hold an array of strings
  • Line 3: Defines a property Items that holds an array of strings.

  • Lines 5–8: The constructor initializes the array with a specific size provided by the holderSize parameter.

  • Line 13: Overrides the ToString method to return a readable list of the items contained in the array.

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

We might define a class like this:

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()
{
return "Items inside: " + string.Join(", ", Items);
}
}
A separate class designed specifically to hold an array of integers
  • Line 4: The Items property is now an int array.

  • Line 8: The array is initialized as an integer array.

This works. However, is this feasible if we need this behavior for many different types? We would end up copying the same code repeatedly and changing only the data type of the internal array.

A better approach uses generics.

Generic types

Generics allow us to define classes with placeholders for types. We specify the actual type when ...