C# - `Required` Attribute for Non-Nullable Reference Types
Keyur Ramoliya
Posted on December 4, 2023
C# 10.0, combined with the introduction of nullable reference types in C# 8.0, allows for more expressive nullability annotations. Particularly noteworthy is the Required
attribute, which can be used in conjunction with nullable reference types to enforce that a property, although nullable, must be provided (e.g., in JSON deserialization scenarios).
Here's how to apply the Required
attribute:
Enable Nullable Context:
Ensure your project file or source files have nullable context enabled (<Nullable>enable</Nullable>
in your.csproj
file or#nullable enable
in your C# files).Apply the
Required
Attribute:
Use theRequired
attribute fromSystem.ComponentModel.DataAnnotations
namespace to indicate that a property is expected, even though it's declared as nullable.
Example:
#nullable enable
using System.ComponentModel.DataAnnotations;
public class UserProfile
{
public string? UserId { get; set; }
[Required]
public string? UserName { get; set; }
}
public static void Main()
{
var profile = new UserProfile
{
UserId = "12345"
// UserName is not set, but it's marked as required.
};
// Logic to validate the profile...
}
In this example, UserName
is a nullable string, but the Required
attribute indicates that it must be provided for a UserProfile
instance to be considered valid. This approach is particularly useful in API development scenarios where you're dealing with data transfer objects (DTOs) that may interact with external data sources like databases or web APIs.
Using the Required
attribute in this manner adds a layer of validation and clarity to your data models, ensuring that necessary properties are not overlooked despite their nullable type.
Posted on December 4, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.