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
- Generic methods/types; constraints
- Variance (in/out) with interfaces & delegates
- Nullable reference types (awareness) & annotations (C# 6 patterns)