What are Properties and its benefits

Properties are class member. The key benefits of properties is that its name can be used in expressions and assignment like a normal variable. It consist get and set accessors.

Get accessor is used to read the value of variable and Set accessor is used to write variable. In the properties, we use value keyword, which is similar to an input parameter of method.

Example of Properties

In the following example, we have first created variable x. now to access the x variable we have created public property xval in which set is assigning the value and get is returning the x.

		
		public class Abc
{    //get for read and set for write
    int x;
     public int xval
    {
        set
        {
            x = value;
        }
        get {  return x;   }
    }

    
}


		

We will call the properties in the following manner:-



		
Abc ab = new Abc();
ab.xval = 10;
Response.Write(ab.xval);

	

Properties with Conditions

If we need to perform any condition before assigning value then we can perfume in the following manner:-

		
public int xval
    {
        set
        {
            if (value > 10)
            {
                x = value;
            }
            else
            {
                x=0;
            }
        }
        get {            return x;        }
    }


So if given value would be greater than 10 then user value will be assigned to x variable otherwise 0 will be assigned.

How to make variable Write Only or Read only using properties

As we know, that set is used to write variable. So in properties if would not use set accessor then it would become Read only. Similarly, if we remove get then it would be Write only.




Auto Implemented Properties

It is possible to implement simple properties without having to explicitly define the variable managed by the properties. This is called Auto Implemented properties. In this type of properties compiler automatically supplies the value.

		
public int z { get; set; }