Example – Intercepting a Payment Process
Interceptors in C# 14 allow developers to intercept or replace method calls at compile time. This makes it possible to add behaviors such as logging, validation, and monitoring without modifying the original code. Unlike traditional approaches that rely on reflection or dynamic proxies, interceptors work during compilation, which improves performance and keeps the codebase cleaner. This feature opens the door to compile-time metaprogramming in .NET, enabling more powerful frameworks and cleaner architecture patterns.
C# 14 Interceptors -- Simple Example
Short Summary
Interceptors in C# 14 allow developers to intercept or replace
method calls at compile time.\
This makes it possible to add behaviors such as logging, validation, and
monitoring without modifying the original code.
Unlike traditional approaches that rely on reflection or dynamic
proxies, interceptors work during compilation, which improves
performance and keeps the codebase cleaner.
------------------------------------------------------------------------
Original Service
csharp
public class PaymentService
{
public void ProcessPayment(decimal amount)
{
Console.WriteLine($"Processing payment: {amount}");
}
}
------------------------------------------------------------------------
Interceptor
csharp
using System.Runtime.CompilerServices;
public static class PaymentInterceptor
{
[InterceptsLocation("Program.cs", line: 12, column: 9)]
public static void ProcessPaymentInterceptor(decimal amount)
{
Console.WriteLine("Payment intercepted!");
Console.WriteLine($"Logging payment amount: {amount}");
if (amount > 1000)
{
Console.WriteLine("High value payment detected.");
}
}
}
------------------------------------------------------------------------
Application Code
csharp
var paymentService = new PaymentService();
paymentService.ProcessPayment(1500);
------------------------------------------------------------------------
Example Output
Payment intercepted!
Logging payment amount: 1500
High value payment detected.
------------------------------------------------------------------------
Why Interceptors Matter
Interceptors enable powerful compile-time features such as:
- Automatic logging
- Validation layers
- Telemetry instrumentation
- Performance monitoring
- Framework-level extensions
All without runtime overhead from reflection or dynamic proxies.
------------------------------------------------------------------------
Conclusion
Interceptors move C# toward compile-time metaprogramming, helping
developers build cleaner and faster architectures.