0Pricing
C# Academy · Lesson

Generic methods/types; constraints

Write generic methods and types; add constraints with where T : … (class, struct, new(), interface/base).

Generics overview

Goal: Reuse code safely with generics.

  • Generic methods & types
  • Constraints: class, struct, new(), interface/base
  • Keep examples small and clear

Generic method

A generic method has a type parameter list, e.g., Identity<T>, and works for many types.

using System;

// Generic method works for any T
public class Program
{
  static T Identity<T>(T value)
  {
    // just returns what it got
    return value;
  }

  public static void Main(string[] args)
  {
    int a = Identity<int>(5);
    string b = Identity<string>("hi");
    Console.WriteLine(a + " & " + b);
  }
}

All lessons in this course

  1. Generic methods/types; constraints
  2. Variance (in/out) with interfaces & delegates
  3. Nullable reference types (awareness) & annotations (C# 6 patterns)
← Back to C# Academy