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.
We'll cover the following...
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 itemsreturn "Items inside: " + string.Join(", ", Items);}}
Line 3: Defines a property
Itemsthat holds an array of strings.Lines 5–8: The constructor initializes the array with a specific size provided by the
holderSizeparameter.Line 13: Overrides the
ToStringmethod 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 integerspublic int[] Items { get; private set; }public IntHolder(int holderSize){Items = new int[holderSize];}public override string ToString(){return "Items inside: " + string.Join(", ", Items);}}
Line 4: The
Itemsproperty is now anintarray.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 ...