During March/2023, Microsoft made Preview 2 of .NET 8 available, with several improvements involving using Data Annotations. More information can be found in an official post on the .NET platform blog:
https://devblogs.microsoft.com/dotnet/announcing-dotnet-8-preview-2/
One of these novelties is the possibility of defining allowed values for a property with the AllowedValuesAttribute type, another structure that becomes part of the System.ComponentModel.DataAnnotations namespace.
In the following listing, we have an example of using AllowedValuesAttribute with the Estado class:
This attribute was associated with the CodRegiao property (region code of a state) and received an array as a parameter with a sequence of possible values, in addition to allowing a description of the inconsistency to be defined in the ErrorMessage property;
The CodRegiao and Nome properties were also marked with RequiredAttribute, indicating the need to fill them in obligatorily.
https://gist.github.com/renatogroffe/a0707697f5616f3d4f918b62122c50a2#file-estado-cs
The next listing shows the contents of the Program.cs file:
An array of type Estado was initialized with 6 instances, to test the use of AllowedValuesAttribute;
The TryValidateObject method of the Validator class (System.ComponentModel.DataAnnotations namespace) was triggered, returning information about inconsistencies according to the Data Annotations specified in the Estado type.
https://gist.github.com/renatogroffe/f7fd5f730cf7742a793e03ffabb23806#file-program-cs
The result of running this Console Application (as of Visual Studio 2022 17.6.0 Preview 2) is shown in the following image, with the inconsistency found highlighted in red:
I also made this example available on GitHub:
https://github.com/renatogroffe/DotNet8-ConsoleApp-AllowedValuesAttribute
If you find this useful, please give a ⭐️ to support. I also invite you to follow me on GitHub!
Leave a comment