c# · level 3 · unit 4 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
An adds a command to a type you do not own.
You cannot edit string or int, but you can add methods that look like theirs. An extension method is a static method whose first parameter has this in front: public static string Initials(this string name). Then "Ada Lovelace".Initials() works as if string always had it.
It must live in a : a class you never make objects from, holding only static members. Declare it after your top-level code. This is how LINQ works: Where and Select are extension methods waiting in System.Linq.
using System;
Console.WriteLine("Ada Lovelace".Initials());
Console.WriteLine("grace brewster hopper".Initials());
Console.WriteLine(1500.AsPounds());
static class Helpers
{
public static string Initials(this string name)
{
string result = "";
foreach (string part in name.Split(' '))
{
result += char.ToUpper(part[0]);
}
return result;
}
public static string AsPounds(this int pence) => $"{pence / 100}.{pence % 100:00} pounds";
} static means a member belongs to the class itself, so you never write new Helpers().
guess first
Repeat after me. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
Console.WriteLine("ha".Repeat(3));
Console.WriteLine("hey ".Repeat(2).Trim().ToUpper());
static class TextTools
{
public static string Repeat(this string text, int times)
{
string result = "";
for (int i = 0; i < times; i++)
{
result += text;
}
return result;
}
}
your turn
Your turn. Count apples properly.
On line 8, add the keyword that turns Plural into an extension method of string. Then choose how many apples on line 3.
output
press run to see what happens
fix it
The space squasher will not compile. Can you fix it?
output
press run to see what happens
- C# says extension methods must be in a non-generic static class. Look at line 5.
- The method is
static, but the class around it is not. - Change line 5 to
static class TextTools, then run.
nailed it
you can extend types you do not own. :D
- An extension method has
thisbefore its first parameter. - It must live in a
staticclass. - LINQ itself is built from extension methods.
new words in your collection
- extension method
- static class
This lesson isn’t saved. A free account remembers every lesson you finish.