Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Implementing C# Interceptors with a Minimal Example

C# interceptors let a method replace calls at specific source locations during compilation. This article shows a minimal source generator, how the compiler resolves intercepted calls, and when the preview feature is practical.

~4 min readC#
#AOP#source generators#runtime interception#method interception
Technical diagram of a source generator placing an interceptor between a caller and the original method.

C# interceptors are an experimental, compile-time feature that lets one method replace a call to another method at a specific source location. The replacement method is marked with [InterceptsLocation], and that attribute identifies the original call by file path, line, and character position. The compiler routes the matching call to the interceptor instead of invoking the original implementation.

Because the attribute must match a call site exactly, source generators are the normal way to build interceptors: a generator can inspect syntax trees, compute the location of a call, and emit an interceptor method that targets that exact position. The feature is preview-only, and the setup depends on the SDK and compiler version. In current previews, you usually need to make InterceptsLocationAttribute visible to the compiler. It is not part of the base class library, so a minimal project often declares it in System.Runtime.CompilerServices:

csharp
namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public sealed class InterceptsLocationAttribute : Attribute { public InterceptsLocationAttribute(string filePath, int line, int character) { } } }

With that attribute available, a source generator can emit interceptor methods. The following incremental generator intercepts one-argument Console.WriteLine calls that pass a string literal:

csharp
using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; [Generator] public sealed class ConsoleInterceptorGenerator : IIncrementalGenerator { public void Initialize(IncrementalGeneratorInitializationContext context) { var calls = context.SyntaxProvider.CreateSyntaxProvider( static (node, _) => node is InvocationExpressionSyntax { Expression: MemberAccessExpressionSyntax { Expression: IdentifierNameSyntax { Identifier.Text: "Console" }, Name: IdentifierNameSyntax { Identifier.Text: "WriteLine" } }, ArgumentList: { Arguments: [{ Expression: LiteralExpressionSyntax { RawKind: (int)SyntaxKind.StringLiteralExpression } }] } }, static (ctx, _) => (InvocationExpressionSyntax)ctx.Node); context.RegisterSourceOutput(calls.Collect(), static (spc, nodes) => { if (nodes.IsEmpty) { return; } var sb = new StringBuilder(); sb.AppendLine("namespace GeneratedInterceptors"); sb.AppendLine("{"); sb.AppendLine(" public static class ConsoleInterceptor"); sb.AppendLine(" {"); foreach (var node in nodes) { var loc = node.GetLocation(); if (loc.SourceTree == null) { continue; } var lineSpan = loc.GetLineSpan(); var fileLiteral = SymbolDisplay.FormatLiteral(loc.SourceTree.FilePath, true); var line = lineSpan.StartLinePosition.Line + 1; var character = lineSpan.StartLinePosition.Character + 1; sb.AppendLine($" [InterceptsLocation({fileLiteral}, {line}, {character})]"); sb.AppendLine(" public static void InterceptWriteLine(string value)"); sb.AppendLine(" {"); sb.AppendLine(" global::System.Console.WriteLine(\"[intercepted] \" + value);"); sb.AppendLine(" }"); } sb.AppendLine(" }"); sb.AppendLine("}"); spc.AddSource("ConsoleInterceptor.g.cs", SourceText.From(sb.ToString(), Encoding.UTF8)); }); } }

The generator filters for calls that look like Console.WriteLine with a string literal argument. For each match, it reads the location through Roslyn's GetLocation().GetLineSpan(). Roslyn reports zero-based line and character positions, while InterceptsLocation expects one-based values, so the generator adds 1 to both. SymbolDisplay.FormatLiteral converts the source-tree path into a valid C# string literal for the attribute; it does not normalize the path. If the path differs between the emitted attribute and the path the compiler uses for the source tree, the interceptor will not be applied.

How the Compiler Resolves an Interceptor

The compiler does not match by method name. It looks for an accessible method with an [InterceptsLocation] attribute whose file path, line, and character correspond to a call in the same compilation. The containing class and method name can differ from the original method, but the interceptor must be callable with the same arguments as the original call. The example generator emits public static methods, so they are accessible from any caller in the assembly.

The file path comparison is ordinary string equality, so exact spelling matters. A relative path in the attribute may not match the absolute path the compiler uses. SyntaxTree.FilePath gives the path in a specific build, but that path can vary across machines or CI agents. This is what makes manually maintained interceptors fragile: moving a call to another line, or building the same source from a different root, can silently stop the interception. A generator recalculates the location each build, so it is the safer choice whenever the call sites are under your control.

Hand-Written Interceptors

Manual interception is possible for one-off experiments. After defining the attribute, a source file can contain:

csharp
[InterceptsLocation("Program.cs", 9, 13)] public static void LogWithTimestamp(string message) { Console.WriteLine($"{DateTime.UtcNow:O} {message}"); }

If line 9, character 13 in Program.cs is a call to Log, the compiler substitutes LogWithTimestamp at that call. The attribute values are not updated automatically, so this approach is easy to break. It is useful for local exploration, but a source generator is usually more maintainable.

Performance and Limitations

Interception is a compile-time rewrite. There is no runtime dispatch, reflection, or proxy indirection added by the feature itself; the generated method is called directly. The cost at runtime is whatever the interceptor method does, such as formatting a string or computing a timestamp.

The main trade-off is build-time complexity. A source generator that scans syntax trees and emits many interceptors can slow the build. The sample uses Collect(), which buffers all matching nodes before generating source, so very large solutions may see additional memory pressure.

Because interceptors are a compile-time feature, they can only affect source that is part of the current compilation. Calls in referenced assemblies that are already compiled are not rewritten, and calls made through dynamic or reflection are not affected. The feature is preview-only, so compiler behavior can change between SDK versions. If your build uses generated source paths, such as CI agents with different roots, verify that the emitted file paths still match.

Where Interceptors Fit in Your Toolbox

C# interceptors fill a narrow slot between runtime AOP frameworks such as Castle DynamicProxy and manual code changes. They provide compile-time substitution without proxy overhead, but they require an opt-in preview setup and exact source locations. Use them when a cross-cutting concern must be applied at many stable call sites and your source generator can reliably emit the required locations. For runtime, dynamic, or dependency-level interception, a runtime proxy or plain refactoring is usually more maintainable.

Try matching browser tools

All tools

Small utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.

All C# guides

More in C#

All C# guides

The guides filed next to this one in C#, in library order.