In this lesson, you will learn how Interceptors allow you to transparently swap out a method call for a different implementation at compile-time to achieve high-performance optimizations.
The "Compile-Time Swap"
Normally, when you call a method in C#, the compiler generates instructions to jump to that specific memory address. An Interceptor is a special mechanism that tells the compiler: "When you see a call to method A at this exact location, don't link to the original method; link to this other method instead."
This happens entirely during the compilation phase, meaning there is zero runtime overhead. You aren't using reflection or dynamic proxies; you are essentially "rewiring" the code before the machine code is even generated.
A Concrete Illustration
Interceptors are primarily used by Source Generators. Imagine you have a method that performs a generic task, but you want to inject a highly optimized, custom version of that method for specific scenarios.
// The original method
public class Logger {
public void Log(string message) => Console.WriteLine(message);
}
// The interceptor
[InterceptsLocation("path/to/file.cs", 10, 12)] // Metadata identifying the exact call
public static class OptimizedLogger {
public static void FastLog(this Logger logger, string message) {
// Optimized, zero-allocation logic here
}
}
When the compiler processes your code, it sees the InterceptsLocation attribute. It looks at the file path, line number, and column provided, finds the call to Log(), and replaces the jump target with FastLog(). To your standard code, it looks like a normal logger.Log("Hello") call, but under the hood, the performance-tuned version is executed instead.
Why use this?
This is a "surgical" tool. It is not meant for daily business logic but for library authors (like those writing JSON serializers or database mappers) who need to squeeze out every bit of performance. By intercepting calls, they can provide specialized, allocation-free implementations that replace slower, general-purpose methods without forcing the developer to change their syntax.
Key Takeaway: Interceptors allow you to replace method calls at compile-time using Source Generators, enabling high-performance custom logic without modifying the original source code or sacrificing runtime speed.