c# · level 3 · unit 1 · lesson 2
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
One method, a fallback. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
using System.Collections.Generic;
var pets = new List<string> { "cat", "dog" };
var empty = new List<string>();
Console.WriteLine(FirstOr(pets, "none"));
Console.WriteLine(FirstOr(empty, "none"));
T FirstOr<T>(List<T> items, T fallback)
{
if (items.Count > 0)
{
return items[0];
}
return fallback;
}
your turn
Your turn. Count the votes.
On line 8, announce the type parameter in the gap after CountOf. Then on line 6, count another meal from the list in both gaps, like curry.
output
press run to see what happens
fix it
The lap timer will not compile. Can you fix it?
output
press run to see what happens
- C# cannot work out
Ton line 5. Compare the two arguments you pass in. lapssaysTisint, but the fallback saysTisstring. Both must agree.- Change the fallback
"none"to0on line 5, then run.
nailed it
one method now fits every type. :D
- A generic method puts
<T>after its name. - Type inference works out
Tfrom the arguments. - Every argument must agree on what
Tis.
new words in your collection
- generic method
- type inference
This lesson isn’t saved. A free account remembers every lesson you finish.