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




