Auto-Implemented Properties of C#



Let me give a simple introduction to auto-implemented properties, which is a feature of C#.Net 3.0 and above.

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.