Auto-Implemented Properties

We've created fields and properties the hard way, we've declared the field and creating the property with getter and setter.
We have been saving some typing by using the visual studio "propfull" snippet that generated the structure of this code for us.
but there is an easier way.

With C# auto-implemented properties, it is fast and easy to create the properties for our application.

Concise property declaration

Auto-implemented properties provide a more concise property declaration.

Implicit backing field

notice there is no field declared when using auto-implemented properties.
A private backing field is declared implicitly behind the scenes, 

so instead of writing six line of code for each property, we can define each property in one line of code.

 Don't allow code in the getter or setter

Auto-Implemented Properties any code in the getter or the setter.

Best used for simple properties

That don't require any additional logic or processing.


Initializing Auto-Implemented Properties

As of c# 6, we can also initialize an Auto-Implemented Property.

public string Category { get; set; } = "Tools";
public intSequenceNumber{ get; set; } = 1;
public Vendor productVendor{ get; set; } = GetDefaultVendor();

As we expect, initializing the property sets the value of the implicit backing field.

Note that an Auto-Implemented Properties initializer can only call static methods.
so, in this case, the GetDefaultVendor must be static.

To initialize the property value by calling a non-static method, 
perform the initialization in the constructor instead.

public Vendor productVendor{ get; set; }
public Product()
{this.ProductVendor= GetVendor();}

So the getVendor here can be static or non-static.

Read-Only Auto-Implemented Properties 


public intInventoryCount{ get; }

Also new in C#6, we can define read-only Auto-Implemented Properties.
Read-only properties have a getter, but no setter.
in this example the public intInventoryCount{ get; } can read but not set.
If needed, the property value can be initialized in the constructor.
public intInventoryCount{ get; }
public Product()
{this.InventoryCount= GetInventoryCount();} 

We can also initialize the read-only  Auto-Implemented Properties
on the declaration.
public intInventoryCount{ get; } = InitializeCount();
Here the value is initialized by calling an InitializeCount(); method.
If the property initializer calls a method, that method must be static.


Auto-Property Best Practices

Do:

Naming

Define a meaningful name
Use PascalCasing

Initialize on the declaration when needed

Avoid:

Naming

Single character name
Abbreviations

If property require code in the getter or the setter









Comments