In a previous article about .NET 8 news, I covered the AllowedValuesAttribute type use, a Data Annotation that integrates the System.ComponentModel.DataAnnotations namespace that allows defining the allowed values for a property:
What’s New in .NET 8: Setting Possible Values with AllowedValuesAttribute
In this new post, I continue the series covering new features of .NET 8, this time describing the use of the DeniedValuesAttribute type (also belonging to the System.ComponentModel.DataAnnotations namespace). As the name suggests, this attribute will indicate values not allowed for a property in a class.
Other .NET 8 news was detailed in the following articles:
.NET 8: First tests with Preview 1 + JSON deserialization improvements
What’s New in C# 12: Using an Alias to Reference a Type
In the following listing, we see an example of using DeniedValuesAttribute with the Projeto class:
This attribute was associated with the TargetFramework property (which corresponds to a .NET version), receiving an array as a parameter and which will contain a sequence of disallowed values. Furthermore, it is also possible to define a description for any inconsistency in the ErrorMessage property;
The TargetFramework and Descricao properties are marked with RequiredAttribute, which will imply that they must be filled in.
The next listing shows the contents of the Program.cs file:
-> A Projeto class array was initialized with five instances, to test the use of DeniedValuesAttribute;
-> The TryValidateObject method of the Validator class (namespace System.ComponentModel.DataAnnotations) was invoked, returning information about inconsistencies according to the Data Annotations configured in the Projeto type.
In the following list we have the result of executing this Console Application (from Visual Studio 2022 17.6.0 Preview 4.0), with the inconsistencies found highlighted in red:
This example is also available on GitHub: https://github.com/renatogroffe/DotNet8-ConsoleApp-DeniedValuesAttribute
If you find this useful, please give a ⭐️ to support. I also invite you to follow me on GitHub!
*The content of this article is the author’s responsibility and does not necessarily reflect the opinion of iMasters.
Leave a comment