Skip to content
Tutorials Center
My learning

Topics

Lesson 70 of 182 ยท Generics

Generics

Learn C# generics from scratch: generic classes, methods and interfaces, type parameters, inference, default(T), and why generics beat object and boxing.

Imagine you need a box that holds one number, and then a box that holds one string, and then a box that holds one customer. You could write three nearly identical classes. Or you could write one class with a hole in it, and fill the hole with a type when you use it. That hole is a type parameter, and a class, struct, interface, method or delegate that has one is called generic.

You have been using generics since the lists lesson: List<int> is the generic class List<T> with int plugged in for T. This lesson shows why generics exist, how to write your own, how the compiler infers type arguments, and what actually happens at runtime. The next lessons build on it: generic constraints, generic methods and delegates, variance and generic math.

The problem generics solve

Before generics (C# 1.0), a reusable container had to hold object, because everything is an object. Let's build such a box and see what is wrong with it:

C# A box of object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Two problems show up. First, the compiler cannot help you: it lets you store a string where you meant a number, and the mistake surfaces later as an InvalidCastException, possibly in a different part of the program. Second, storing an int in an object boxes it (the value is copied into a new object on the heap), and casting it back unboxes it. That costs memory and time; we measure it below.

Your first generic class

Replace object with a type parameter, written in angle brackets after the class name. By convention it is called T (for "type"), or TKey, TValue, TResult when there are several and the role matters:

C# A generic Box of T

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Box<int> and Box<string> are two different constructed types built from one generic type definition Box<T>. In Box<int>, T means int everywhere: the constructor takes an int, Value is an int, and no cast is needed. The mistake from the previous example is now a compile error, which is the best time to find a bug.

The words to keep straight:

  • Type parameter: the placeholder in the declaration (T in class Box<T>).
  • Type argument: the real type you supply (int in Box<int>).
  • Open generic type: Box<> or Box<T> with no argument yet; closed or constructed: Box<int>.

Generic classes with more than one parameter

A class may have several type parameters. A tiny pair type shows it:

C# Two type parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The last line prints the real runtime type, Pair`2[System.Int32,System.String]. The backtick-2 means "generic type with two type parameters". In the standard library, Dictionary<TKey, TValue> and KeyValuePair<TKey, TValue> work the same way, and ValueTuple<T1, T2> is what (int, string) really is.

A real example: a generic stack

Generic containers are where this pays off. Here is a small stack that stores any type, with a growing array inside:

C# MyStack of T

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Inside the class, T can be used almost like any type: in arrays (T[]), fields, parameters and return types, and new T[2] is fine. What you can not do with a bare T is call members you have not been promised, such as item.Length or a + b; the compiler only knows that T is some type. Constraints are how you make such promises.

default(T): the "nothing" value of any type

You will often need a "blank" T: for an empty slot, a "not found" result, a reset. The expression default(T), or just default when the type is clear, gives the zero value of whatever T turns out to be: 0 for numbers, false for bool, null for reference types, and a struct with all fields zeroed.

C# default for each T

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The ! after default is the "null-forgiving" operator. With nullable reference types on, default for an unconstrained T might be null, and the compiler would warn that you put a possible null in a non-nullable T. Writing default! says "I know". The alternative is to declare the result T?, which in an unconstrained generic means "T or null/default".

Generic methods and type inference

A single method can be generic without the whole class being generic. The type parameter list goes after the method name:

C# A generic method with inference

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The compiler infers the type argument from the arguments you pass, so you almost never write Last<int>(...). Inference works from arguments only, not from the expected return type: T Create<T>() can't be called as int x = Create(); because there is nothing to infer from, and you must write Create<int>(). More on this in generic methods.

Generic interfaces

Interfaces can be generic too, and the framework is full of them: IEnumerable<T>, IComparer<T>, IEquatable<T>, IList<T>. A generic interface lets an implementer say exactly what type it works with, with no casts:

C# A generic repository interface

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The repository doesn't know what a Book is. It receives a function that extracts the id, a typical way to keep generic code free of assumptions. (A constraint such as where T : IHasId would be the other common solution.)

Generics vs object: the cost of boxing

Besides safety, generics are faster for value types. A non-generic ArrayList stores object, so every int is boxed. List<int> stores real ints inside a real int[]. We can count allocated bytes on the current thread to see the difference without relying on timings:

C# Counting the boxing cost

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Each boxed int takes a 24-byte object plus an 8-byte reference slot in the array, while a List<int> takes 4 bytes. Fewer allocations also mean less garbage-collection work later (see boxing and value semantics).

How generics work at runtime

C# generics are reified: the type information survives to runtime, unlike Java's erased generics. typeof(T) works inside generic code, new List<int>() and new List<string>() are really different types, and obj is List<int> is a meaningful test.

The JIT compiler creates specialized machine code per type argument for value types (List<int> and List<double> get their own optimized code, with no boxing). For reference types it shares one compiled version, since all references look the same to the CPU. You normally don't think about this, but it explains two facts: generics over value types are as fast as hand-written code for that type, and a static field in a generic class exists once per constructed type:

C# One static per closed type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Because each closed type has its own statics, a generic class is a handy place to cache per-type data, a trick shown in generic methods and delegates. It's also a classic surprise when someone expects one shared counter.

Pitfalls and guidelines

  • Name type parameters clearly. A lone T is fine; with two or more, use descriptive names with a T prefix: TKey, TValue, TInput, TOutput.
  • Don't write a generic type when a concrete one will do. Generics add reading cost. Add the type parameter when you actually have two or more types to support.
  • Don't over-nest. Dictionary<string, List<Tuple<int, Func<string>>>> is a signal to introduce a named type or an alias (using Scores = System.Collections.Generic.Dictionary<string, int>;).
  • Prefer the generic collections. Use List<T>, Dictionary<TKey, TValue> and friends; the non-generic ones in System.Collections are only for legacy code.
  • You can't use T as a base class or call new T() freely. class Foo<T> : T doesn't compile, and new T() needs the new() constraint.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main advantage of List<int> over ArrayList for storing integers?

    List<int> keeps ints in a real int[] and rejects other types at compile time, while ArrayList stores object, which boxes every int and needs casts.
  2. 2. In the declaration class Cache<TKey, TValue>, what are TKey and TValue?

    They are type parameters, placeholders in the declaration. Cache<string, int> supplies the type arguments string and int.
  3. 3. What does default(T) return when T is int, and when T is string?

    default is the zero value of the type: 0 for numeric types and null for reference types such as string (not an empty string).
  4. 4. How many separate copies of the static field exist in static class Counter<T> { public static int Count; } if you use Counter<int>, Counter<string> and Counter<int> again?

    Each constructed type (Counter<int>, Counter<string>) has its own statics. Using Counter<int> twice refers to the same type, so there are two copies.
  5. 5. Which is true about C# generics at runtime?

    C# generics are reified: the runtime knows the type arguments, which is why typeof(T), is List<int> and per-type specialization work.

Summary

  • A generic type or method has type parameters (T) that callers fill with type arguments; Box<int> and Box<string> are different constructed types.
  • Generics give compile-time type safety and avoid the casts and boxing of object-based code.
  • Inside generic code, a bare T is opaque: you can store it and pass it around, but only constraints let you call members on it.
  • default gives the zero value of T; type inference lets you call Last(numbers) without writing Last<int>.
  • Generics are reified in .NET: typeof(T) works, value-type instantiations are specialized, and each closed type has its own static fields.
  • Generic interfaces such as IRepository<T> and IEnumerable<T> describe behavior that works for many types.

Next: Generic Constraints