C# - Properties

Properties

A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.

Properties Overview

  • Properties enable a class to expose a public way of getting and setting values, while hiding implementation or verification code.

  • A get property accessor is used to return the property value, and a set accessor is used to assign a new value. These accessors can have different access levels.

  • The value keyword is used to define the value being assigned by the set accessor.

  • Properties that do not implement a set accessor are read only.

  • For simple properties that require no custom accessor code, consider the option of using auto-implemented properties.

The get Accessor

The body of the get accessor resembles that of a method. It must return a value of the property type. The execution of the get accessor is equivalent to reading the value of the field. For example, when you are returning the private variable from the get accessor and optimizations are enabled, the call to the get accessor method is inlined by the compiler so there is no method-call overhead. However, a virtual get accessor method cannot be inlined because the compiler does not know at compile-time which method may actually be called at run time. The following is a get accessor that returns the value of a private field name:

      class Date
        {
            private int day;  // the day field
            public int Day    // the Day property
            {
                get
                {
                    return day;
                }
            }
        }

When you reference the property, except as the target of an assignment, the get accessor is invoked to read the value of the property. For example:

      Date dob = new Date();
      //...
      System.Console.Write(dob.Day);  // the get accessor is invoked here

The get accessor must end in a return or throw statement, and control cannot flow off the accessor body.

The set Accessor

    class Date
        {
            private int day;  // the day field
            public int Day    // the Day property
            {
                get
                {
                    return day;
                }
                set
                {
                    day = value;
                }
            }
        }

When you assign a value to the property, the set accessor is invoked by using an argument that provides the new value. For example:

     Date doj = new Date();
     doj.Day = 25;  // the set accessor is invoked here                
     System.Console.Write(doj.Day);  // the get accessor is invoked here

Auto-Implemented Properties

In C# 3.0 and later, auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors. They also enable client code to create objects. When you declare a property as shown in the following example, the compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.

    class Date
    {
        public int Day { get; set; }
        public int Month { get; set; }
        public int Year { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Date doj = new Date();
            doj.Day = 22;
            doj.Month = 5;
            doj.Year = 2005;
            Console.WriteLine("DOJ is :{0}/{1}/{2}", doj.Day, doj.Month, doj.Year);
          
        }

Object Initializers

Object initializers let you assign values to any accessible fields or properties of an object at creation time without having to invoke a constructor followed by lines of assignment statements. The object initializer syntax enables you to specify arguments for a constructor or omit the arguments (and parentheses syntax). The following example shows how to use an object initializer with a named type, date and how to invoke the default constructor. Note the use of auto-implemented properties in the date class.

       Date doj = new Date{Day=22,Month=5,Year=2005};