- Knowledge for Developers.
Follow Us
Home Backend What’s New in .NET 8: Setting Possible Values ​​with AllowedValuesAttribute

What’s New in .NET 8: Setting Possible Values ​​with AllowedValuesAttribute

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:

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.

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.

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:

If you find this useful, please give a ⭐️ to support. I also invite you to follow me on GitHub!

Written by
Renato Groffe

Worked as a consultant in systems development activities for over 15 years. Microsoft MVP (Most Valuable Professional) and MTAC (Multi-Plataform Technical Audience Contributor) program participant. Bachelor in Information Systems, specialization in Software Engineering, and MBA in Business Intelligence. He is also a lecturer and technical author on portals and specialized magazines, focusing on Microsoft technologies and good practices in the software area.

Leave a comment

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *

Related Articles


How to Create a Skill for Amazon’s Virtual Assistant Alexa

If you didn’t know, it is not necessary for an Amazon Echo...


The APIs role in a 5G world

5G is about to revolutionize how we connect and use technology daily....


EF Core using AsNoTracking with Identity Resolution

Today we will see the consequences of using AsNoTracking with the Identity...


Understand key features added in ASP.NET Core 7.0

Version 7.0 of the .NET platform brought many new features in this...