CallerArgumentExpression always null

Viewed 1186

I'm experimenting with [CallerArgumentExpression] in C# 8:

static void Main(string[] args)
{
    try
    {
        Program query = null;
        Argument(query != null, "Ooops");
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
    }
}

public static void Argument(bool condition, string message, [CallerArgumentExpression("condition")] string conditionExpression = null)
{
    if (!condition) throw new ArgumentException(message: message, paramName: conditionExpression);
}

However, I cannot get the value of conditionExpression to be anything other than null.

I've been using this https://blog.mcilreavy.com/articles/2018-08/caller-argument-expression-attribute and a few other pages and, of course, good as a guide, but I can't get it to work.

2 Answers

The feature was implemented in Roslyn compiler that supports C# 10, even if you are not using C# 10.

Related