Delen via


Properties (C# Programming Guide)

Properties are members that provide a flexible mechanism to read, write, or compute the values of private fields. 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.

In this example, the TimePeriod class stores a time period. Internally the class stores the time in seconds, but a property named Hours enables a client to specify a time in hours. The accessors for the Hours property perform the conversion between hours and seconds.

Example

class TimePeriod
{
    private double seconds;

    public double Hours
    {
        get { return seconds / 3600; }
        set { seconds = value * 3600; }
    }
}


class Program
{
    static void Main()
    {
        TimePeriod t = new TimePeriod();

        // Assigning the Hours property causes the 'set' accessor to be called.
        t.Hours = 24;

        // Evaluating the Hours property causes the 'get' accessor to be called.
        System.Console.WriteLine("Time in hours: " + t.Hours);
    }
}
// Output: Time in hours: 24

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. For more information, see Asymmetric Accessor Accessibility (C# Programming Guide).

  • 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. For more information, see Auto-Implemented Properties (C# Programming Guide).

C# Language Specification

For more information, see the following sections in the C# Language Specification:

  • 1.6.7.2 Properties

  • 10.2.9.1 Member names reserved for properties

  • 10.7 Properties

See Also

Concepts

C# Programming Guide

Property Design

Reference

Using Properties (C# Programming Guide)

Indexers (C# Programming Guide)