Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force a property initialization when initializing an object

Tags:

c#

.net

using System.ComponentModel.DataAnnotations;

public class User
{
    [Required]
    public string FirstName { get; set; }

    [Required]
    public string LastName { get; set; }
}

User user = new User
{
    LastName = "Jane"
};

FirstName and LastName are required, why does the code let me initialize a user without FirstName? How can I force it so that FirstName must have a value as well?


2 Answers

C# 11 introduces this new feature of being able to require a property when initializing an object with the required keyword.

You can do something like this:

public class User
{
    public required string FirstName { get; set; }
    public required string LastName { get; set; }
}

User user = new User
{
    FirstName = "Caffè",
    LastName = "Latte"
};

If you need the constructor, you need to add the [SetsRequiredMembers] attribute to it, like this:

public class User
{
    public required string FirstName { get; set; }
    public required string LastName { get; set; }

    [SetsRequiredMembers]
    public User(string firstName, string lastName) => (FirstName, LastName) = (firstName, lastName);
}

User user = new User("Caffè", "Latte");
like image 79
Kaffu Avatar answered Feb 18 '26 15:02

Kaffu


You can add a constructor that forces you to initialize the property:

public class User
{
    [Required]
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public User(string firstName)
    {
       FirstName = firstName;
    }
}

This will be impossible:

User user = new User
{
    LastName = "Jane"
};

You'll have to do it like this:

User user = new User("something")
{
    LastName = "Jane"
};

Because you can still pass null to your constructor, you also might check this:

public User(string firstName)
        {
           if(firstName == null)
           {
              throw new ArgumentNullException(nameof(firstName));
           }
           FirstName = firstName;
        }
like image 44
SomeBody Avatar answered Feb 18 '26 15:02

SomeBody



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!