3

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

Ian Kemp
  • 28,293
  • 19
  • 112
  • 138
Avrohom Yisroel
  • 8,555
  • 8
  • 50
  • 106
  • 1
    Just thrown your code into a VS2022 Net 6 Console app and have no problem with it. Works as expected. – Ralf Dec 07 '21 at 17:10
  • @Ralf Yup, I had created the project in VS2019, so even though I changed it to .NET6, it was still targetting C#9 – Avrohom Yisroel Dec 07 '21 at 17:18

1 Answers1

4

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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
aryeh
  • 610
  • 5
  • 13
  • Duh, ain't oi the stoopid one! I had created it in VS2019 and changed the target to net6.0, forgetting that this still left me with C#9. Thanks – Avrohom Yisroel Dec 07 '21 at 17:17