×

c# · level 3 · unit 4 · lesson 3

  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

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().