Property Design 

In general, methods represent actions and properties represent data. Properties are used like fields, meaning that properties should not be computationally complex or produce side effects. For additional information about property design, see Indexed Property Design and Property Change Notification Events.

The following guidelines help ensure your properties are well designed.

Do create read-only properties if the caller should not be able to change the value of the property.

Be aware that the mutability of the property type affects what the end user can change. For example, if you define a read-only property that returns a read/write collection, the end user cannot assign a different collection to the property but can modify the elements in the collection.

Do not provide set-only properties.

If the property getter cannot be provided, use a method to implement the functionality instead. The method name should begin with Set followed by what would have been the property name. For example, AppDomain has a method called SetCachePath instead of having a set-only property called CachePath.

Do provide sensible default values for all properties, ensuring that the defaults do not result in a security hole or an extremely inefficient design.

Do allow properties to be set in any order even if this results in a temporary invalid object state.

Do preserve the previous value if a property setter throws an exception.

Avoid throwing exceptions from property getters.

Property getters should be simple operations without any preconditions. If a getter might throw an exception, consider redesigning the property to be a method. This recommendation does not apply to indexers. Indexers can throw exceptions because of invalid arguments.

It is valid and acceptable to throw exceptions from a property setter.

Portions Copyright 2005 Microsoft Corporation. All rights reserved.

Portions Copyright Addison-Wesley Corporation. All rights reserved.

For more information on design guidelines, see the "Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries" book by Krzysztof Cwalina and Brad Abrams, published by Addison-Wesley, 2005.

See Also