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
csharp
// User-written "Program.cs"
partial class Program
{
public void PerformOperation()
{
Initialize();
}
public void Initialize()
{
// ...
}
}
// Code-generated "Program.generated.cs"
static class ProgramInterceptors
{
[InterceptsLocation("Program.cs", 6, 8)]
public static void SpecialInitialize(this Program program)
{
// ...
}
}csharp
// 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
- Interceptors are opt-in and require explicit project configuration
- The interceptor must be a
staticmethod whose signature matches the intercepted call. For instance methods, the first parameter is the receiver and is annotated withthisjust like an extension method C# 3.0 - The containing namespace must be listed in the
<InterceptorsPreviewNamespaces>MSBuild property