liveBook · Manning

Extension

As explained in .NET in Action, Second Edition

An extension method is a static method that can be invoked with instance-method syntax on a type without modifying or inheriting from that type.

An extension method adds callable behavior to an existing type without modifying or inheriting from it. Define it as a static method in a static class, mark its first parameter with this, and invoke it with instance-method syntax. section 2.8

Listing 2.17 Extension method to get every other character in a string
public static class MyStringExtensions                      #1
{
  public static string EveryOtherCharacter(this string s)   #2
  {
    char[] newChars = new char[s.Length / 2 + 1];           #3
    int sPos, nPos;                                         #4
    for (sPos = 0, nPos = 0;
         sPos < s.Length;
         sPos += 2, nPos++)
    {
      newChars[nPos] = s[sPos];                             #5
    }
  
    return new string(newChars, 0, nPos);                   #6
  }
}

The EveryOtherCharacter example shows the required static class, this-annotated string parameter, implementation loop, and returned value. section 2.8

Keep these behavioral boundaries in mind:

  • Invoke the method as though it belongs to the extended type, such as "abcdefghijklmn".EveryOtherCharacter(). section 2.8
  • Access only the extended object and its public members; extension methods cannot reach internal or private members. section 2.8
  • Chain library extensions such as WithParsed and WithNotParsed on ParserResult to handle successful and unsuccessful parsing. section 2.8

How .NET in Action, Second Edition covers it

How deep it goes
Defines declaration syntax, invocation syntax, chaining, and visibility limits through focused C# examples.
Examples
Uses EveryOtherCharacter on string values and WithParsed or WithNotParsed on ParserResult objects.
What it assumes
Assumes familiarity with C# classes, methods, static members, parameters, and object-oriented inheritance.
What you can do after
Build it from scratch by defining a static extension class and invoking its method with instance syntax.
How it connects
Connects extension methods with static classes, sealed classes, interfaces, abstract classes, delegates, and fluent method chaining.

Also explained in

Compare how 5 books explain extension →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of .NET in Action, Second Edition. The section links point to the parts of the book it draws on.