🚀 C# ile Programlamaya Giriş: Kodlamaya İlk Adımını At, Kendi Projelerini Geliştirmeye Başla!
00HOME
07GLOSSARY 08TAGS ♡MY LIST ⌕SEARCH
TRENG

Generic Types: The Secret of List<T>

You find out what the T in List<T> is, write your own generic method and class that work with any type, and learn about where constraints and Dictionary<TKey, TValue>.

Since the arrays lesson you have been writing List<double> and List<string>. The same List class holds voltage readings one day and channel names the next, and each time it accepts only its own type. The feature behind this is called generic (type-independent) programming. In a measurement system you do not want to write the same "keep the last N values" logic separately for voltage, for temperature and for event messages. With generics you write it once and use it safely with any type.

The problem: keeping everything in object

Every type in C# derives from object, so you can put anything into an object variable. At first sight this looks like a "one box for every type" solution. But the price is high: you have to cast the value when you take it back out, and a wrong type only shows up while the program is running.

object[] box = { 3.3, 5.0, "12V" };   // anything fits
double sum = 0;

foreach (object o in box)
{
    try
    {
        sum += (double)o;
    }
    catch (InvalidCastException)
    {
        Console.WriteLine($"'{o}' is not a double!");
    }
}
Console.WriteLine($"Sum: {sum}");
'12V' is not a double!
Sum: 8.3

The compiler did not object when the text "12V" went into the array. The error was only caught at run time. In a data acquisition program running in the field, that means a service crashing at midnight. Generic types move this error to compile time.

A generic method: write once, use with any type

After the method name you declare a type parameter in angle brackets: <T>. T is a placeholder; when you call the method, the compiler replaces it with the real type. The method below finds the largest element in int, double and string arrays:

static T Max<T>(T[] array) where T : IComparable<T>
{
    T max = array[0];
    foreach (T x in array)
    {
        if (x.CompareTo(max) > 0)
            max = x;
    }
    return max;
}

Console.WriteLine(Max(new[] { 3, 9, 4 }));
Console.WriteLine(Max(new[] { 3.3, 2.9, 3.6 }));
Console.WriteLine(Max(new[] { "CH1", "CH3", "CH2" }));
9
3.6
CH3

We did not write Max<int>(...) when calling; the compiler worked out the type from the argument. where T : IComparable<T> is a constraint: it says "T must be a type that can be compared with its own kind". Thanks to the constraint, we can call CompareTo inside the method. CompareTo returns a positive number if the first value is larger, a negative one if it is smaller, and zero if they are equal.

A generic class: your own "latest readings" buffer

Now let us write a small sibling of List<T>: a buffer that keeps only the last N values. Data loggers use exactly this structure to show "the last 10 readings" on screen.

var voltages = new LatestReadings<double>(3);
foreach (double v in new[] { 3.1, 3.3, 3.2, 3.6 })
    voltages.Add(v);
Console.WriteLine(string.Join(" | ", voltages.All()));

var events = new LatestReadings<string>(2);
events.Add("Started");
events.Add("Threshold exceeded");
events.Add("Back to normal");
Console.WriteLine(string.Join(" | ", events.All()));
Console.WriteLine($"Capacity: {events.Capacity}, filled: {events.Count}");

class LatestReadings<T>
{
    private readonly List<T> _data = new();
    public int Capacity { get; }
    public int Count => _data.Count;

    public LatestReadings(int capacity) => Capacity = capacity;

    public void Add(T value)
    {
        _data.Add(value);
        if (_data.Count > Capacity)
            _data.RemoveAt(0);          // drop the oldest
    }

    public List<T> All() => new List<T>(_data);   // hand out a copy
}
3.3 | 3.2 | 3.6
Threshold exceeded | Back to normal
Capacity: 2, filled: 2

The <T> next to the class name makes T usable everywhere in the class. When you create a LatestReadings<double>, Add accepts only doubles; voltages.Add("3.4") does not compile. We did not write the code twice, and we did not give up type safety. Letting All() return a copy instead of the inner list is a deliberate choice too: outside code cannot damage the buffer's contents.

Constraints and two type parameters

Constraints tell the compiler what T can do. The most common ones:

ConstraintMeaning
where T : structT must be a value type (int, double, bool...)
where T : classT must be a reference type (classes, string...)
where T : new()T must have a parameterless constructor; you can write new T() inside
where T : IComparable<T>T must implement this interface
where T : SensorT must be Sensor or a class derived from it

A type can also have more than one type parameter. The example you will use most is Dictionary<TKey, TValue>: it gives fast access from a key to a value. Let us keep the latest value of each sensor by channel name:

var latest = new Dictionary<string, double>();
latest["T1"] = 23.5;
latest["T2"] = 24.1;
latest["T1"] = 23.9;          // same key: overwrites

foreach (var (channel, value) in latest)
    Console.WriteLine($"{channel}: {value}");

if (latest.TryGetValue("T3", out double t3))
    Console.WriteLine(t3);
else
    Console.WriteLine("T3 not measured yet");
T1: 23.9
T2: 24.1
T3 not measured yet

Reading a missing key as latest["T3"] throws a KeyNotFoundException; if you are not sure, use TryGetValue. Do not rely on the order of items in a dictionary: the order is not guaranteed, and here it just happened to match the insertion order.

Common mistakes

  • Using operators on an unconstrained T: Operations such as a > b or a + b do not compile for an unconstrained T, because not every type has these operators. For comparisons use an IComparable<T> constraint and CompareTo.
  • Forgetting the constraint for new T(): If you want to create a new T inside the method, add where T : new() to the signature.
  • Treating List<double> as List<object>: Although a double is an object, a List<double> is not a List<object>; you cannot assign one to the other. Otherwise you could add text to the double list through the object list.

Exercise

Write a Clamp<T>(value, min, max) method that works with any type: it returns min if the value is below the range, max if it is above, and the value itself if it is inside. Try it by clamping a 10-bit ADC reading of 1100 to 0-1023, and -3.5 V and 2.4 V to the 0-5 V range.

Hint: Use IComparable<T> as the constraint. value.CompareTo(min) < 0 means "value is less than min". In the double tests write the limits as 0.0 and 5.0 so all three arguments have the same type.

Solution

static T Clamp<T>(T value, T min, T max) where T : IComparable<T>
{
    if (value.CompareTo(min) < 0) return min;
    if (value.CompareTo(max) > 0) return max;
    return value;
}

Console.WriteLine(Clamp(1100, 0, 1023));     // ADC reading
Console.WriteLine(Clamp(-3.5, 0.0, 5.0));    // voltage
Console.WriteLine(Clamp(2.4, 0.0, 5.0));
1023
0
2.4

.NET also has a ready-made Math.Clamp for numbers, but your own generic version works with any type that implements IComparable<T>, even dates.

With generic types you can build reusable, type-safe structures. In the next lesson we will learn about delegates, which carry methods around like variables, and about sensor threshold events.

// Spot the bug +10 XP

Exactly one line below is wrong. Click the faulty line.

// Mini quiz

Click an option; you will see right away, with the reason, whether it is correct or not.

1. What does the <double> part of List<double> specify?
2. Why does static T Max<T>(T a, T b) => a > b ? a : b; not compile?
3. What is the main benefit of storing data in a generic type instead of object?

Mark it when you finish: your progress is saved and you earn +20 XP.

Tip: ← → keys let you move between lessons.