A while ago, when I was looking at read-only auto-properties I started comparing them to the previous method of making a property read-only by making it private. When it comes down to it there are a few differences how they can be initialised and read/written to. At the time I put together this example. Comments explain where and how each property can be accessed.
void Main()
{
Person firstPerson=new Person(new DateTime(2001, 10, 16));
// Unrestricted access to FirstName and LastName
firstPerson.FirstName="John";
firstPerson.LastName="Jones";
// Cannot access Date Of Birth, other than via consructor or within class membes internally
//firstPerson.DateOfBirth= new DateTime(1926, 03, 27);
//firstPerson.Age = 34;
// Accessing readonly property directly produces a compile time error
firstPerson.ChangeDateOfBirth(new DateTime(1926, 03, 27));
// Uncomment if runnning with LinqPad
//Console.WriteLine(firstPerson);;
}
public class Person{
// Unrestricted access
public string FirstName{get; set;}
public string LastName{get; set;}
// Accessible only by Constructor
public DateTime DateOfBirth {get;} // Date
// Accessible by Contructors and internally to the class members
public int Age {get; private set;}
public Person(DateTime dob){
DateOfBirth = dob;
Age=-1;
CalculateAge();
}
public void CalculateAge(){
// Validat Date set before calculation
// Implementation to calculate the age from the DateOfBirth
DateTime today = DateTime.Today;
Age = today.Year - DateOfBirth.Year;
if (today.Month < DateOfBirth.Month || (today.Month == DateOfBirth.Month && today.Day < DateOfBirth.Day))
{
Age--;
}
}
public void ChangeDateOfBirth(DateTime dateOfBirth){
// Compile time error when trying to access readonly property
//DateOfBirth = dateOfBirth;
}
}
I have made this example available as a Gist here

You must be logged in to post a comment.