I'm making classes and I wanted to know the differnce in the application of the getters and setters.
e.g.
public class Employee
{
private string forename;
public string Forename { get { return forename; } }
private string surname;
public string Surname { get { return surname; } }
private int age;
}
In what I have made I have 'private string forename;'. Because it doesn't have {get;set;} is it a variable instead of a field in the class? Also because it is private I have used a property with the same name in order to access forename. I guess my question is what is the point in having the separate Forename/forename if I have to write {get; set;} for the private one as well as the public one. Is there a better way to write the fields? Couldn't I just have written:
private string forename{ get { return forename; } }
e.g. for my password field I have:
private string password;
public string Password
{ set
{
bool validPassword = false;
if (value.Length > 7 & value.Length < 15)
{
if (value.Any(char.IsLower))
{
if (!value.Contains(" "))
{
if (value.Any(char.IsUpper))
{
string specialChar = @"%!@#$%^&*()?/>.<,:;'\|}]{[_~` =-" "\"";
char[] specialCharArray = specialChar.ToCharArray();
foreach (char ch in specialCharArray)
{
if (value.Contains(ch))
{
validPassword = true;
Console.WriteLine("Password has been changed");
break;
}
}
}
}
}
}
Couldn't I have just put this all in a {set} on the private password?
CodePudding user response:
password
is a private field, and Password
is a public property.
You are correct that you could put this logic directly in the set block of the private password field.
But by using a property with a set
block instead of a field with a set block, you can specify the logic for validating and assigning the password value at a single place, and you can expose the password
value to other codes through the property. It makes your code easier to maintain and understand.
user can simply assign a password like this employee.Password = "@$@#%@#%@#!";
without knowing the internal details. you can also change this implementation in future without breaking anything.
In short properties are the wrapper around fields.
Forename
property only has a getter, which means that it is a read-only property.
Here is the official documentation of properties, you can refer this as well.