csharp / expert
Snippet
Defensive Programming using Compiler-Injected Metadata
Compiler Attributes like CallerMemberName and CallerFilePath allow the C# compiler to inject metadata into method calls automatically. This is essential for advanced error handling and testing, as it provides precise context for failures in production logs without the performance cost of capturing a full stack trace.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using System.Runtime.CompilerServices;public class Validator{public static void AssertNotNull(object val,[CallerMemberName] string member = "",[CallerFilePath] string file = "",[CallerLineNumber] int line = 0){if (val == null){throw new ArgumentNullException($"Null detected in {member} at {file}:{line}");}}}
Breakdown
1
[CallerMemberName] string member = ""
Instructs the compiler to provide the name of the method or property that called this assertion.
2
throw new ArgumentNullException($"Null detected in {member} at {file}:{line}");
Creates a descriptive error message using the injected compile-time metadata.