Local extension methods

Mark
1 min readMay 4, 2021

Y’all know what extension methods are…

public static class Extensions
{
public static bool IsNullOrEmpty(this string value) =>
string.IsNullOrEmpty(value);
}

They’re great and they give us the syntactic sugar to make code readable…

string name = GetName();
if (name.IsNullOrEmpty()) // Readable
DoSomething();
if (string.IsNullOrEmpty(name)) // 1990’s calling
DoSomething();

The problem is that sometimes you want that sugar but the implementation is so niche that you don’t even want to use it in a sibling class…

public class SomeService
{
private class SomeInternalRepresentation
{
...
}
public void DoSomething(SomeExternalRepresentation data)
{
var data_ = data.Convert();
...
}
private static SomeInternalRepresentation Convert(
this SomeExternalRepresentation data) => ...
}

Instead you’re forced to do this…

public class SomeService
{
private class SomeInternalRepresentation
{
...
}
public void DoSomething(SomeExternalRepresentation data)
{
var data_ = Convert(data);
...
}
private static SomeInternalRepresentation Convert(
SomeExternalRepresentation data) => ...
}

… or this …

using MyNamespace.SomeServiceExtensions;namespace MyNamespace
{
public class SomeService
{
internal class SomeInternalRepresentation
{
...
}
public void DoSomething(SomeExternalRepresentation data)
{
var data_ = data.Convert();
...
}
}
namespace SomeServiceExtensions
{
internal class Extensions
{
internal static SomeService.SomeInternalRepresentation
Convert(this SomeExternalRepresentation data) => ...
}
}
}

… or something else equally hideous.

In the era of local functions etc., it boggles the mind that MS hasn’t given us something so simple as local extensions. Hell, we should even be able to…

public void DoSomething(Employee employee)
{
static bool IsRetarded(this Employee employee) =>
employee.Employer == "Microsoft";
if (employee.IsRetarded())
Sigh();
}

--

--