March 30, 2026

C# Compiler "CallerArgumentExpression"

Here is an example usage of the "CallerArgumentExpression". It allows you to capture a copy of some compiled code that evaluates to a value expression


void Main()
{
    var x = 34;
    var y = 23;
    Assert.That(x > y, $"{x} > {y}");
    x = 20;
    Assert.That(x > y, $"{x} > {y}");
}

// You can define other methods, fields, classes and namespaces here
public static class Assert
{
    public static void That(
         bool condition,
         string message = "",
         [CallerArgumentExpression("condition")] string expression = "",
         [CallerMemberName] string memberName = "",
         [CallerFilePath] string sourceFilePath = "",
         [CallerLineNumber] int sourceLineNumber = 0)
    {
        if (!condition)
        {
            var fullMsg = $"{sourceFilePath}:{sourceLineNumber} {memberName} - Assertion \"{expression}\" evaluated to FALSE: {message}";
            Trace.WriteLine(fullMsg);
            Console.WriteLine(fullMsg);
        }
    }
}

In this case the expression "x > y" that is passed in as the value of "bool condition" parameter is inserted by the compiler into the "string expression" parameter. In this example, the first Assert passes and outputs nothing but the second one outputs the following:

C:\...\Temp\LINQPad8\_hxysxhku\ewejlm\LINQPadQuery:7 Main - Assertion "x > y" evaluated to FALSE: 20 > 23

No comments: