What is the best practice to add data annotation validators to private class members without having public set (If there is a way)
public class Employee{
//private fields
//constructors
[Required(ErrorMessage = "Required field")]
[DataType(DataType.Text, ErrorMessage = "Invalid input for firstname")]
public string FirstName { get { return this.firstName; } }
}
In C#, a Property represents a private field with bound Get and/or Set methods. It does all the encapsulation for you, so what you are trying to solve is already done.
The code you wrote:
class Employee
{
public string FirstName { get; set; }
}
What the compiler sees:
class Employee
{
private string _firstName;
public string GetFirstName()
{
return _firstName;
}
public void SetFirstName(string firstName)
{
_firstName = firstName;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.