Extension Methods
Extension methods are static methods called with instance syntax.
How it works
Add discoverable operations to existing types.
The this modifier on the first parameter declares an extension target. The original string type is not modified.
Runnable C# example
Program.cs
using System;
static class StringExtensions
{
public static string Truncate(this string value, int length)
=> value.Length <= length ? value : value[..length] + "…";
}
class Program
{
static void Main() => Console.WriteLine("CodeUtility".Truncate(4));
}
Code…Practice with the debugger
Set a breakpoint on an important assignment or condition, click Debug, and inspect the local values before stepping to the next line.