Pages

Tuesday, May 21, 2013

Properties in c#

Properties are members that provide a flexible mechanism to read ,write or compute the values of private fields.
->we can also modify the data present in the private variable.
->properties become little bit faster than method
Note:When you need to use of properties ?
 Ans:when you wanted to read/write data from/to  to a private variable.

Types of properties :

1.Read-only Properties
2.write-only Properties
3.Read write Properties

*We can not change both access modifier for a given  properties(either set or get).
->Private set modifier is used to control the access to object's property value.
->Public set modifier is directly accessing the object's property value

Sample code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Properties : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
       Patent p = new Patient();
        p.Age=36;
        int age=p.Age;
        Response.Write(p.Age);
    }
}
Public class Patient    
   {                               // in case of properties class no need create object to accessed variable
    private int _age;
    public int Age;
  }

get
   {
    return _age;
   }
 set
   {
    _age=value;
    }
 }


 

No comments:

Post a Comment