Refer to my article http://www.c-sharpcorner.com/UploadFile/hirenvisavadiya/8528/
You can see the following class:
public class Customer
{
private int _customerID;
private string _companyName;
private Phone _phone;
public int CustomerID
{
get { return _customerID; }
set { _customerID = value; }
}
public string CompanyName
{
get { return _companyName; }
set { _companyName = value; }
}
public Phone Phone
{
get { return _phone; }
set { _phone = value; }
}
}
But in auto-implemented properties we do not need to handle variables like _cutoemrID, _phone etc as in the above snippet.
public class Customer
{
public int CustomerID { get; set; }
public string CompanyName { get; set; }
public Phone Phone{ get; set; }
public string ToString()
{
return "Customer ID: " + CustomerID.ToString() + Environment.NewLine + "Company Name: " + CompanyName + Environment.NewLine + "Phone number: " + Phone.ToString();
}
}
And see the phone class:
public class Phone
{
public string CountryCode { get; set; }
public string AreaCode { get; set; }
public string PhoneNumber { get; set; }
public string ToString()
{
string phonenumber = "Phone number:";
if (!string.IsNullOrEmpty(CountryCode)) phonenumber += CountryCode + "-";
if (!string.IsNullOrEmpty(AreaCode)) phonenumber += AreaCode + "-";
phonenumber += PhoneNumber;
return phonenumber;
}
}
In the above examples, the compiler creates private fields which are accessed through the property's get and set assessors.
savan savaniPosted Apr 5, 2017, 7:35 AM
So auto implemented properties works same as fields in this case. Then why don't we use public fields instead of public properties?
Thomas MapotherPosted Aug 2, 2011, 3:17 AM
Hi Hiren, Is there any other option we have to access private fields without using get and set assessors...?