Section86.1:Auto-implementedproperties
Auto-implementedpropertieswereintroducedinC#3.
Anauto-implementedpropertyisdeclaredwithanemptygetterandsetter(accessors):
publicboolIsValid{get;set;}
When an auto-implemented property is written in your code, the compiler creates a private anonymous field that can only be accessed through the property’s accessors.
Theaboveauto-implementedpropertystatementisequivalenttowritingthislengthycode:
privatebool_isValid;
publicboolIsValid
{
get{return_isValid;}
set{_isValid=value;}
}
Auto-implementedpropertiescannothaveanylogicintheiraccessors,forexample:
publicboolIsValid{get;set{PropertyChanged(“IsValid”);}}//Invalidcode
Anauto-implementedpropertycan howeverhavedifferentaccessmodifiersforitsaccessors:
publicboolIsValid{get;privateset;}
C#6allowsauto-implementedpropertiestohavenosetteratall(makingitimmutable,sinceitsvaluecanbeset only inside the constructor or hard coded):
publicboolIsValid{get;}
publicboolIsValid{get;}=true;
Formoreinformationoninitializingauto-implementedproperties,readtheAuto-propertyinitializersdocumentation.
Section86.2:DefaultValuesforProperties
SettingadefaultvaluecanbedonebyusingInitializers(C#6)
publicclassName
{
publicstringFirst{get;set;}=”James”;
publicstringLast{get;set;}=”Smith”;
}
Ifitisreadonlyyoucanreturnvalueslikethis:
publicclassName
{
publicstringFirst=>”James”;
publicstringLast=>”Smith”;
}
Gettersareusedtoexposevaluesfromclasses.
stringname;publicstringName
{
get{returnthis.name;}
}
Settersareusedtoassignvaluestoproperties.
stringname;publicstringName
{
set{this.name=value;}
}
Section86.5:AccessingProperties
classProgram
{
publicstaticvoidMain(string[]args)
{
PersonaPerson=newPerson(“AnnXenaSample”,newDateTime(1984,10,22));
//exampleofaccessingproperties(Id,Name&DOB)
Console.WriteLine(“Idis: \t{0}\nNameis:\t‘{1}’.\nDOBis:\t{2:yyyy-MM-dd}.\nAgeis:
\t{3}”,aPerson.Id,aPerson.Name,aPerson.DOB,aPerson.GetAgeInYears());
//exampleofsettingproperties
aPerson.Name=” HansTrimmer “;
aPerson.DOB=newDateTime(1961,11,11);
//aPerson.Id=5;//thiswon’tcompileasId’sSETmethodisprivate;soonlyaccessible withinthePersonclass.
//aPerson.DOB=DateTime.UtcNow.AddYears(1);//thiswouldthrowaruntimeerrorasthere’s validationtoensuretheDOBisinpast.
//seehowourchangesabovetakeeffect;notethattheNamehasbeentrimmed
Console.WriteLine(“Idis: \t{0}\nNameis:\t‘{1}’.\nDOBis:\t{2:yyyy-MM-dd}.\nAgeis:
\t{3}”,aPerson.Id,aPerson.Name,aPerson.DOB,aPerson.GetAgeInYears());
Console.WriteLine(“Pressanykeytocontinue”); Console.Read();
}
}
publicclassPerson
{
privatestaticintnextId=0;
privatestringname;
privateDateTimedob;//datesareheldinUTC;i.e.wedisregardtimezones
publicPerson(stringname,DateTimedob)
{
this.Id=++Person.nextId;
this.Name=name;
this.DOB=dob;
}
publicintId
{
get;
privateset;
}
publicstringName
{
get{returnthis.name;} set
{
if(string.IsNullOrWhiteSpace(value))thrownewInvalidNameException(value);
this.name=value.Trim();
}
}
publicDateTimeDOB
{
get{returnthis.dob;} set
{
if(value<DateTime.UtcNow.AddYears(-200)||value>DateTime.UtcNow)thrownew InvalidDobException(value);
this.dob=value;
}
}
publicintGetAgeInYears()
{
DateTimetoday=DateTime.UtcNow;
intoffset=HasHadBirthdayThisYear()?0:-1;
returntoday.Year-this.dob.Year+offset;
}
privateboolHasHadBirthdayThisYear()
{
boolhasHadBirthdayThisYear=true;
DateTimetoday=DateTime.UtcNow;
if(today.Month>this.dob.Month)
{7
hasHadBirthdayThisYear=true;
}
else
{
if(today.Month==this.dob.Month)
{
}
else
{
}
}
hasHadBirthdayThisYear=today.Day>this.dob.Day;
hasHadBirthdayThisYear=false;
returnhasHadBirthdayThisYear;
}
}
publicclassInvalidNameException:ApplicationException
{
conststringInvalidNameExceptionMessage=”‘{0}’isaninvalidname.”; publicInvalidNameException(stringvalue):
base(string.Format(InvalidNameExceptionMessage,value)){}
}
publicclassInvalidDobException:ApplicationException
{
const string InvalidDobExceptionMessage = “‘{0:yyyy-MM-dd}’ is an invalid DOB. Thedatemust notbeinthefuture,orover200yearsinthepast.”;
public InvalidDobException(DateTime value): base(string.Format(InvalidDobExceptionMessage,value)){}
}
Section86.6:Read-onlyproperties
Declaration
Acommonmisunderstanding,especiallybeginners,haveisread-onlypropertyistheonemarkedwithreadonly
keyword.That’snotcorrectandinfactfollowingisacompiletimeerror:
publicreadonlystringSomeProp{get;set;}
Apropertyis read-onlywhenit onlyhasa getter.
publicstringSomeProp{get;}
Usingread-onlypropertiestocreateimmutableclasses
publicAddress
{
publicstringZipCode{get;}
publicstringCity{get;}
publicstringStreetAddress{get;}
publicAddress(
stringzipCode,
stringcity,
stringstreetAddress)
{
if(zipCode==null)
throw new ArgumentNullException(nameof(zipCode));
if(city==null)
thrownewArgumentNullException(nameof(city)); if
(streetAddress==null)
thrownewArgumentNullException(nameof(streetAddress));
ZipCode=zipCode;
City=city;
StreetAddress=streetAddress;
}
}
Section86.7:VariousPropertiesinContext
publicclassPerson
{
//Idpropertycanbereadbyotherclasses,butonlysetbythePersonclass
publicintId{get;privateset;}
//Namepropertycanberetrievedorassigned
publicstringName{get;set;}
privateDateTimedob;
//DateofBirthpropertyisstoredinaprivatevariable,butretrievedorassignedthroughthe publicproperty.
publicDateTimeDOB
{
get { return this.dob; }
set{this.dob=value;}
}
//Agepropertycanonlyberetrieved;it’svalueisderivedfromthedateofbirth
publicintAge
{
get
{
intoffset=HasHadBirthdayThisYear()?0 : -1;
returnDateTime.UtcNow.Year-this.dob.Year+offset;
}
}
//thisisnotapropertybutamethod;thoughitcouldberewrittenasapropertyifdesired.
privateboolHasHadBirthdayThisYear()
{
bool hasHadBirthdayThisYear = true;
DateTimetoday=DateTime.UtcNow;
if (today.Month>this.dob.Month)
{
hasHadBirthdayThisYear=true;
}
else
{
if(today.Month==this.dob.Month)
{
hasHadBirthdayThisYear=today.Day>this.dob.Day;
}
else
{
hasHadBirthdayThisYear=false;
}
}
returnhasHadBirthdayThisYear;
}
}
About us and this blog
We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.
Request a free quote
We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.
Subscribe to our newsletter!
More from our blog
See all postsRecent Posts
- Chapter120:YieldKeyword 20/05/2024
- Chapter119:LockStatement 19/05/2024
- Chapter118:Makingavariablethreadsafe 18/05/2024