Skip to content

Instantly share code, notes, and snippets.

@davidarobinson
Last active May 26, 2019 22:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidarobinson/2c9989b399bc514bb226710bdf9fb57a to your computer and use it in GitHub Desktop.
Save davidarobinson/2c9989b399bc514bb226710bdf9fb57a to your computer and use it in GitHub Desktop.
A linqpad file demonstrating the differences between C#6 read-only auto-properties and previous private set properties
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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment