Where was [CallerArgumentExpression] when I needed it?

1/25/2022

On our current project at work, we have a perfect use for CallerArgumentExpressionAttribute. Unfortunately we're still on .NET 4.7. This would have helped a lot.

We have a task of importing a (very long) single line of column-delimited text. This line gets split up by columns and placed in an ImportData class and parsed in a function similar to this:

public void ProcessData(ImportData data)
{
    DateTime receivedDate = parseDate(data.RECEIVED_DATE);
    DateTime acceptedDate = parseDate(data.ACCEPTED_DATE);
}

If a parsing error occurred, say in "ACCEPTED_DATE", we need to report an error such as:

"Bad date provided for ACCEPTED-DATE"

Notice the underscore becomes a dash. This message is then sent back to the team providing the text file.

Along comes CallerArgumentExpressionAttribute (for .NET CORE)

Starting with .NET Core 3.0, the CallerArgumentExpressionAttribute attribute can be added to functions that actually provides the name of the variable (or expression) used when calling the function!

A simple example is as follows:

void ProcessResult(
    int result, 
    [CallerArgumentExpression("result")] string expression = "")
{
    Console.WriteLine($"{expression} is {result}");
}

void Test()
{
    int Age = 12;
    ProcessResult(Age);
}

The following is printed:

Age is 12

Applied to our code

We can now use that in our parseDate function, and easily be able to provide an appropriate Warning, without making any change to the original code above:

private DateTime parseDate(string theDate, 
        [CallerArgumentExpression("theDate")] string expression = "")
{
    DateTime result;
    if (!DateTime.TryParse(theDate, out result))
    {
        string columnName = expression.Substring
                (expression.LastIndexOf('.') + 1).Replace('_', '-');
        logWarning($"Bad date provided for {columnName}");
    }

    return result;
}

...that is once we finally get to migrate to .NET CORE! (hint, hint!)


Please register or login to add a comment.

Comments (displaying 1 - 1):
No comments yet! Be the first...


  • C#/.NET/Core
  • T-SQL
  • HTML/Javascript/jQuery
  • ASP.NET/MVC
  • .NET Core
  • ADO.NET/EF
  • WPF
  • Xamarin/MAUI
  • Windows 10
  • SQL Server 20xx
  • Android
  • XBox One
  • Skiing
  • Rock Climbing
  • White water kayaking
  • Road Biking