0

This code will pass, and shouldn't.

public record EmptyString([Required]string Name);
var context = new ValidationContext(src, null, null);

var es = new EmptyString("");

bool valid = Validator.TryValidateObject(src, context, results, true);

Assert.IsTrue(valid);
// ???? this shows up as valid! When it's clearly NOT!

Add property: in front of Required, and suddenly it works. But first code (above) does not give a compile error!

// add property to line below see
public record EmptyString([property:Required]string Name);
var context = new ValidationContext(src, null, null);

var es = new EmptyString("");
bool valid = Validator.TryValidateObject(src, context, results, true);

// suddenly we get correct behaviour.
Assert.IsFalse(valid);

is this a C# 9 bug, or am I missing something? Txs

Alan

snowcode
  • 1,033
  • 10
  • 24
  • 2
    from the [docs](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/records#properties) _Attributes can be applied to the synthesized auto-property and its backing field by using `property:` or `field:` targets for attributes syntactically applied to the corresponding record parameter._ It first sample you're applying an attribute for constructor parameter – Pavel Anikhouski Jan 17 '21 at 20:22
  • Considering that a record is immutable, and has shortcut constructor syntax, requiring that the constructor parameter MUST be supplied seems perfectly reasonable. it makes no sense to apply the attribute to the Property, because it CANNOT be set by a user. So while I understand why ... technically it is correct according the docs, it's a really bad design, and fails any "reasonability" test. Just because it's technically correct according to some document, doesnt mean it's not a bug. – snowcode Jan 18 '21 at 21:22
  • Also, if .. .applying the attributes to a constructor property is actually wrong, then it should show up as a compiler error. The fact it does NOT show up as a compiler error suggests it's actually legitimate, for some other purpose I don't know about, and that can't be to actually apply it to the constructor property as you suggest, because then it would actually work. I think the bug is in Microsoft.DataAnnotations Validate, most likely. I will upvote your reply, because I think it IS a bug in Microsoft.DataAnnotations and we have to simply REMEMBER that exact usage, and not rely on compiler – snowcode Jan 18 '21 at 21:25

0 Answers0