Automatic Properties have evolved a bit over the years as new C# versions were released and I think I'll summarize here its different features.
The most common, basic case is this:
public string Name {get; set;}
Notice that the C# compiler creates a private, backing field for the property: <Name>k__BackingField.
We can also mark the setter as private:
public int Age{get; private set;}
In C# 6 two features where added: Automatic Property Initializers:
public string Country {get; set;} = "Unknown";
And Getter Only Autoproperties:
//immutable, can be set also from constructor
public string Dni {get;} = "Unknown";
public string ID {get;}
//use examples:
public Person(string dni)
{
this.ID = "unknownID";
this.Dni = dni;
}
In the above case, the compiler no longer generates a setter. The private backing field is directly set, either in that assignment, or in the class constructor.
Finally, C# 9, paying further attention to the Immutability trend, has added Init only setters.
//immutable, can be set also from constructor and from object literal
public string MotherLanguage {get; init;} = "Unknown";
//use examples:
public Person(){}
public Person(string motherLanguage)
{
this.MotherLanguage = motherLanguage;
}
var p2 = new Person
{
MotherLanguage = "Francais"
};
This "init" does not involve any addition at the bytecode level, it's just translated into a normal setter. The interesting thing with it is that it can be set not only inline or in the constructor, but also from an Object literal. Contrary to the previous, "Getter only autoproperties" where I said that if set from the constructor it's done by directly setting the private backing field, here, both from the constructor or the Object literal, the compiler emits a call to the setter.
Regarding my statements about getters being or not being generated, the backup fields and so on... I've been using AvaloniaILSpy, an excellent multiplatform frontend to ILSpy. I've been using it on my Ubuntu laptop and it runs nicely.
No comments:
Post a Comment