Skip to content
Tutorials Center
My learning

Topics

Lesson 72 of 182 ยท Generics

Generic Methods and Delegates

Learn C# generic methods and delegates: type inference rules, explicit type arguments, Func and custom delegates, per-type caching and reflection basics.

A generic class puts a type parameter on the whole type. A generic method puts it on one method only, and that method can live anywhere: in a normal class, in a static helper class, or inside a generic class with its own, different parameters. Generic methods are the workhorses behind LINQ (Select<TSource, TResult>), Array.Sort<T>, Enumerable.Empty<T>() and countless utility functions you will write yourself.

This lesson covers how generic methods are declared and called, exactly how the compiler infers type arguments (and when it gives up), generic delegates such as Func<T, TResult> and your own, static members in generic types, a clever per-type caching trick, and a short preview of reflection with generics.

Declaring and calling a generic method

The type parameter list comes after the method name. It can be used in the return type, the parameters and the body:

C# Swap and First

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.

You never wrote Swap<int>(...). The compiler looked at the arguments, found int and int, and filled in T itself. That's type inference.

How type inference works

Inference looks at the argument expressions, not at what you do with the result. In outline:

  1. For each argument, the compiler gathers what it tells about the type parameters.
  2. If every type parameter ends up with exactly one best candidate, the call compiles.
  3. If it can't determine some parameter, you get CS0411: The type arguments for method ... cannot be inferred from the usage.

Mixed arguments are where beginners trip. Here is what works and what doesn't:

C# Mixed argument types

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 third call compiles too. For int and double arguments the candidate set is {int, double}, and int converts implicitly to double but not the other way around, so double wins and the output is 7.5. If you change it to Larger(3, "x"), there is no common type, inference fails and the compiler reports CS0411.

The rule that causes the most grief: the return type is not used. Look at this:

C# Return type is not an input (fails on purpose)

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 reports error CS0411: The type arguments for method 'Make<T>()' cannot be inferred from the usage. Try specifying the type arguments explicitly. and the fix is Make<int>(). Explicit type arguments are always allowed, and are needed when there are no arguments to infer from, or when you want a different type than inference would choose.

Lambdas take part in inference in two phases: first the compiler fixes the type parameters it can learn from ordinary arguments, then it uses those to type the lambda's parameters, and finally the lambda's return type fixes the remaining parameters. That's why Map(numbers, n => n.ToString()) works (below): TIn comes from the list, TOut from what the lambda returns.

C# Inference through lambdas

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.

Generic methods in generic classes

A generic method can sit inside a generic class. The two sets of parameters are independent, and a method parameter should not reuse the class's name (the compiler warns that it hides it, CS0693):

C# Class parameter plus method parameter

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.

Generic delegates

Because a delegate type is a "type of method", it can be generic too. The framework gives you the family you already know: Func<..., TResult> for methods that return something, Action<...> for those that don't, Predicate<T> for bool-returning tests, Comparison<T> for sorting, and Converter<TInput, TOutput>. Here they are doing real jobs:

C# The built-in generic delegates

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.

You can declare your own generic delegate when a custom name reads better than a Func:

C# A custom generic delegate

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 in in delegate bool Validator<in T> is a variance annotation, covered in covariance and contravariance. Delegates themselves, including multicast and invocation, are the subject of the delegates lesson.

A generic method can also accept method groups (the name of a method without parentheses). Once the compiler knows the parameter types, it resolves the right overload and infers the return type from it:

C# Method groups and generic 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.

int.Parse has several overloads. With TIn already fixed to string by the first argument, the compiler picks int.Parse(string) and reads int off its return type.

Static members and generic caching per type

Recall that every closed generic type has its own static fields. A generic static class can use that as a per-type cache: do expensive work the first time for a type, and the result is stored for free in a static field. The Comparer<T>.Default and EqualityComparer<T>.Default in the library work like this.

C# Per-type cache in a static generic class

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 things make this trick safe: the runtime runs the static initializer exactly once per closed type, and it does so under a lock. Compare it to a Dictionary<Type, string> that you'd have to lock yourself. Use it for things like pre-built serializers, comparers or delegates compiled for a type.

Local generic functions and generic extension methods

Local functions can be generic as well, and extension methods are very often generic: they are how LINQ is built. An extension is just a static generic method whose first parameter has this:

C# A generic extension method

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.

A string is an IEnumerable<char>, so InGroupsOf<char> works on it with no extra code. That is the power of generic methods over a general interface.

Reflection with generics (preview)

Sometimes the type is known only at runtime, for example from a configuration file. The reflection API lets you build closed types and call generic methods then. This is slower and loses compile-time checking, so reserve it for plugin systems and frameworks. More in reflection and attributes.

C# Building generic types at run time

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.

In a file with top-level statements the compiler generates a class called Program; declaring partial class Program lets us add a public static method to it. Normally you would write the generic call directly and let inference do the work.

Pitfalls

  • Overusing generics. If a method is only ever called with int, make it take int.
  • Hiding the class's T. A method Foo<T> inside class Bar<T> triggers warning CS0693 and is almost always a mistake. Rename the method parameter.
  • Expecting return-type inference. var x = Make(); and int n = Make(); both fail to infer. Pass an argument or write Make<int>().
  • Boxing through object parameters. A generic method taking T avoids boxing for value types, while Describe(object value) boxes. Prefer T.
  • Reflection in hot paths. MakeGenericMethod and Invoke are slow; build once, cache the delegate (the per-type cache trick above), and reuse it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given static T Make<T>() where T : new() => new T();, which call compiles?

    Type inference uses the arguments, never the target type or return type. With no arguments, you must give the type argument explicitly: Make<int>().
  2. 2. Which describes how Map<TIn, TOut>(List<TIn> source, Func<TIn, TOut> convert) is inferred in Map(numbers, n => n.ToString())?

    The compiler first learns TIn from the list argument, gives the lambda parameter that type, and then infers TOut from the lambda's return value.
  3. 3. What is special about a static field in a generic class such as static class Cache<T> { public static int Hits; }?

    Each constructed type has its own statics, which makes generic static classes good per-type caches.
  4. 4. In delegate bool Validator<in T>(T value);, what does the generic parameter allow compared with an ordinary delegate?

    The in keyword makes T contravariant: a validator for any Animal is also a valid validator for a Cat. Variance is covered in the next lesson.
  5. 5. Why is calling a generic method through reflection (MakeGenericMethod + Invoke) usually avoided in normal code?

    Reflection defers type checking to run time and is much slower than a direct call. Use it only when the type truly is unknown until run time, and cache the result.

Summary

  • A generic method declares its own type parameters (Swap<T>), usable in its signature and body, even inside a non-generic class.
  • The compiler infers type arguments from the arguments (including lambda return types), never from the expected return type; use explicit arguments when inference has nothing to work with.
  • Func, Action, Predicate<T>, Comparison<T> and Converter<TIn, TOut> are the standard generic delegates; declare your own when a name documents intent better.
  • Every closed generic type has its own static members, so a generic static class is a thread-safe per-type cache.
  • Generic extension methods over IEnumerable<T> are how LINQ works.
  • Reflection can build generic types and methods at run time, at a cost in speed and safety.

Next: Covariance and Contravariance