Properties
Properties are flexible mechanisms for reading, writing, or computing a private field's value.
They can be implemented like public data members, however, they are actually accessors. Review syntax below:
public int ProductID { get { return _productID; } set { _productID = result; } }
Properties allow a class to reveal a public means of retrieving and establishing values while keeping implementation and verification code hidden. The get property accessor returns the property value, and a set property accessor assigns a value. These accessors are assigned different access levels. The value keyword defines the value assigned by the set accessor. Properties which do not use the set accessor are read-only. Review example code for property use below:
public class Product { private int _productID; private string _manufacturerName; public int ProductID { get { return _productID; } set { _productID = value; } } public string ManufacturerName { get { return _manufacturerName; } set { _manufacturerName = value; } } }
C# offers simple options which do not require the use of accessor code. These properties are autoimplemented. These properties make client code and internal code easier to access, reduce LOC, allow validation before changes are made to data, and more. Examine the difference between standard properties and auto-implemented properties below:
public class Product { private int _productID; private string _manufacturerName; public int ProductID { get { return _productID; } set { _productID = value; } } public string ManufacturerName { get { return _manufacturerName; } set { _manufacturerName = value; } } } public class Product { public int ProductID { get; set; } public string ManufacturerName { get; set; } public ProductInfo (int _productID, string _manufacturerName) { ManufacturerName = _manufacturerName; ProductID = _productID; } public string ToString() { return "Product ID: " + ProductID.ToString() + Environment.NewLine + "Manufacturer Name: " + ManufacturerName; } }