Reputation:
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?
Upvotes: 13
Views: 11557
Reputation: 447
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");
Upvotes: 31
Reputation: 422
The [Required]
attribute is used for model binding. If you require the class to have the FirstName property you should add a constructor.
public class User
{
[Required]
public string FirstName { get; set; }
public string LastName { get; set; }
public User(string firstName)
{
FirstName = firstName;
}
}
User user = new User("FirstName")
{
LastName = "Jane"
};
Upvotes: 3
Reputation: 8743
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;
}
Upvotes: 6