I'm trying to use the CallerArgumentExpression
attribute, in conjunction with the suggestion for validating records found here, but the expression is always null. I am doing this in a .NET6 Core console application. The exact same code works fine in LinqPad 7 (.NET6).
I have a base record
that contains common validation methods (pretty much copied from that other answer)...
public record CommonValidation {
internal static bool NonEmptyOrNullString(string s, [CallerArgumentExpression("s")] string expr = default) {
if (string.IsNullOrWhiteSpace(s)) {
throw new ArgumentException($"{expr} cannot be null or empty");
}
return true;
}
internal static bool NonZeroInt(int n, [CallerArgumentExpression("n")] string expr = default) {
if (n < 0) {
throw new ArgumentException($"{expr} cannot be negative");
}
return true;
}
}
I can then create a record
as follows...
public record Address(string Street, string City, string State, string Country, string Postcode) : CommonValidation {
private bool _ = NonEmptyOrNullString(Street)
&& NonEmptyOrNullString(City)
&& NonEmptyOrNullString(State)
&& NonEmptyOrNullString(Country)
&& NonEmptyOrNullString(Postcode);
}
If I try to create an Address
with an empty State
...
Address a = new("5 My Street", "Somewhere", "", "Oz", "12345");
...then the exception is thrown, but the expr
variable is null. As I said, the exact same code works fine in LinqPad, even though both are using the same version of .NET/C#.
Anyone able to explain what's going wrong in the console app? Thanks
CodePudding user response:
Visual Studio 2019 doesn't support C# 10. Make sure you're using Visual Studio 2022. LinqPad 7 does which is why it works there.