Pages

Properties

v Properties

   Another type of class member is the property. As a general rule, a property combines a field with the methods that access it.

   You will often want to create a field that is available to users of an object, but you want to maintain control over the operations allowed on that field.

    For instance, you might want to limit the range of values that can be assigned to that field. While it is possible to accomplish this goal through the use of a private variable along with methods to access its value, a property offers a better, more streamlined approach.

   Properties are similar to indexers. A property consists of a name along with get and set accessors. The accessors are used to get and set the value of a variable.

   The key benefit of a property is that its name can be used in expressions and assignments like a normal variable, but in actuality the get and set accessors are automatically invoked. This is similar to the way that an indexer’s get and set accessors are automatically used.

   The general form of a property is shown here:








type name
{
get
{
// get accessor code
}
set
{
// set accessor code
}
}

   Here, type specifies the type of the property, such as int, and name is the name of the property. Once the property has been defined, any use of name results in a call to its appropriate accessor. The set accessor automatically receives a parameter called value that contains the value being assigned to the property.
    
   Here is a simple example that defines a property.

using System;

class test
{
    private int no;

    public int pno
    {
        get
        {
          return no;
        }
        set
        {
            no = value;
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        test t=new test();
        t.pno=13;
        int temp=t.pno;
        Console.WriteLine("No. is = {0}",temp);
        Console.ReadLine();
    }
}

   Output

No. is = 13

Þ   Property Restrictions

   Properties have some important restrictions. First, because a property does not define a storage location, it cannot be passed as a ref or out parameter to a method.

   You cannot overload a property. (You can have two different properties that both access the same variable, but this would be unusual.)

   A property should not alter the state of the underlying variable when the get accessor is called. Although this rule is not enforced by the compiler, violating it is semantically wrong. A get operation should be nonintrusive.


No comments:

Post a Comment