×

c# · level 3 · unit 1 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A brings its own type parameter.

A whole class does not need to be generic: one method can be. A generic method puts its type parameter after its name: T LastOf<T>(List<T> items). Inside, T means whatever type the list holds, and the answer comes back as that type.

When you call it, you rarely say what T is. C# looks at the arguments and works it out. This is : pass a List<string> and a string comes back.

The keyword var uses the same trick for variables. In var drinks = new List<string>(), C# sees the right side and makes drinks a List<string>.

using System;
using System.Collections.Generic;

var drinks = new List<string> { "tea", "coffee", "cocoa" };
var scores = new List<int> { 12, 30, 18 };
string drink = LastOf(drinks);
int score = LastOf(scores);
Console.WriteLine($"{drink} {score + 2}");

T LastOf<T>(List<T> items) => items[items.Count - 1];

You can still name the type yourself, as in LastOf<string>(drinks), when that reads more clearly.