Skip to content

Interceptors C# 12.0code generation

Allow a method to declare it should be used instead of another method it specifies.

Interceptors allow a method to declare it should be used in place of another call elsewhere in the project's source code by specifying a filepath, line and column using the InterceptsLocationAttribute.

This is useful for code generation scenarios where a code-generated methods could add new functionality but could not replace or remove existing code unless that code was specifically written in a way to permit replacement or removal.

Code

C#
// User-written "Program.cs"
partial class Program
{
    public void PerformOperation()
    {
        Initialize();
    }

    public void Initialize()
    {
        // ...
    }
}

// Code-generated "Program.generated.cs"
partial class Program
{
    [InterceptsLocation("Program.cs", 6, 8)]
    public void SpecialInitialize()
    {
        // ...
    }
}
C#
// User-written "Program.cs"
partial class Program
{
    private Action initializer = () => Initialize();
    partial void PerformOperationStartHook();

    public void PerformOperation()
    {
        initializer = Initialize;
        PerformOperationStartHook();
        initializer();
    }

    public void Initialize()
    {
        // ...
    }
}

// Code-generated "Program.generated.cs"
partial class Program
{
    partial void PerformOperationStartHook()
    {
        initializer = SpecialInitialize;
    }

    public void SpecialInitialize()
    {
        // ...
    }
}

Notes

  • You can use static methods too providing the first parameter is the instance type and is annotated with this just like an extension method C# 3.0.

More information