DEV Community

Cover image for C# - `Required` Attribute for Non-Nullable Reference Types
Keyur Ramoliya
Keyur Ramoliya

Posted on

C# - `Required` Attribute for Non-Nullable Reference Types

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:

  1. 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).

  2. Apply the Required Attribute:
    Use the Required attribute from System.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...
}
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)