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

theramoliya

Keyur Ramoliya

Posted on December 4, 2023

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.

💖 💪 🙅 🚩
theramoliya
Keyur Ramoliya

Posted on December 4, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related