We are providing online training of realtime Live project on Asp.Net MVC with Angular and Web API. For more information click here. If you have any query then drop the messase in CONTACT FORM

Monday, October 26, 2015

Auto-Implemented properties in MVC

When we write applications based on Object-Oriented Programming concepts, we need to define a lot of classes. When we define classes in C#, we need to define member variables and properties. Usually, we define member variables as private and we will expose these member variables with corresponding public properties. This gives us an overhead as we are forced to define private variables just to expose them as properties.

With C# 3.0, this has been solved with the support of auto-implemented properties. The auto-implemented properties make our code small and easy to write. With auto-implemented properties, we can avoid such member variables we created for properties. 
see the example below

public class Customer{
private int customerID;
private string customerName;
private string phone;
private string pinCode;

public int CustomerID
{
get { return customerID; }
set { customerID = value; }
}
public string CustomerName
{
get { return customerName; }
set { customerName = value; }
}
public string Phone
{
get { return phone; }
set { phone = value; }
}
public string PineCode
{
get { return pinCode; }
set { pinCode = 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 { getset; }
    public string CustomerName { getset; }
    public string Phone{ getset; }
   public string PineCode{ getset; }
    public string ToString()
    {
return "Customer ID: " + CustomerID.ToString() + Environment.NewLine +"Customer Name: " + CustomerName+ Environment.NewLine + "Phone number: " + Phone + Environment.NewLine + +"Pin Code: " + PineCode;
    }

 

And see the phone class:
public class Phone
{
    
    public string CountryCode { getset; }
    public string AreaCode { getset; }
    public string PhoneNumber { getset; }
    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 that are accessed through the property's get and set assessors.

No comments: