C
C#5mo ago
Jason_Bjorn

✅ [AllowedValue] not doing anything

Why is my code allowing the name "Jimmy" ?
using System.ComponentModel.DataAnnotations;

public class Foo
{
[AllowedValues(new object [] {"Bill", "Bob"}, "Entered illegal name")]
public string Name { get; set; }
}

class Program
{
public static void Main()
{
Foo f = new()
{
Name = "Jimmy" // works ???
};
}
}
using System.ComponentModel.DataAnnotations;

public class Foo
{
[AllowedValues(new object [] {"Bill", "Bob"}, "Entered illegal name")]
public string Name { get; set; }
}

class Program
{
public static void Main()
{
Foo f = new()
{
Name = "Jimmy" // works ???
};
}
}
13 Replies
oke
oke5mo ago
The AllowedValues attribute seems to be for code clarity/readability, not actually enforcing the value. But, it's a property, so you can just implement that check in the setter.
oke
oke5mo ago
AllowedValuesAttribute Class (System.ComponentModel.DataAnnotations)
Specifies a list of values that should be allowed in a property.
oke
oke5mo ago
It just says "specifies a list of values that should be allowed"
Anton
Anton5mo ago
There's got to be at least an analyzer for this It would pretty easy to detect -- just look at constructors where that property is assigned a constant. Roslyn detects that automatically. More complex rules will have to be coded manually though
jcotton42
jcotton425mo ago
@Jason_Bjorn all of DataAnnotations is for things like GUIs and ASP.NET when doing input validation. They have no meaning to the compiler.
Jason_Bjorn
Jason_BjornOP5mo ago
the docs are pretty bleak for that one would be nice if this was documented but thank you
jcotton42
jcotton425mo ago
It is. Attributes interpreted by the compiler are documented as such.
Jason_Bjorn
Jason_BjornOP5mo ago
Where does it say that
jcotton42
jcotton425mo ago
What do you mean? If the docs for an attribute don’t say “the compiler looks at this attribute” (paraphrasing), the compiler won’t be looking at the attribute.
oke
oke5mo ago
i think this one is mostly on microsft (or the team of people who update the docs) it would be nice if there were a tag or something that clarified that this does nothing another thing i noticed for this, even if the attribute actually did something, this still wouldnt work as intended because the constructor only takes an array of objects and notes nothing about the last being an error message so it could be rewritten as
public class Foo
{
[AllowedValues("Bill", "Bob")]
public string Name { get; set; }
}
public class Foo
{
[AllowedValues("Bill", "Bob")]
public string Name { get; set; }
}
Jason_Bjorn
Jason_BjornOP5mo ago
thank you
Unknown User
Unknown User5mo ago
Message Not Public
Sign In & Join Server To View
MODiX
MODiX5mo ago
If you have no further questions, please use /close to mark the forum thread as answered
Want results from more Discord servers?
Add your server