Jeffrey Richter, in his excellent book CLR Via C#, stated that he dislikes properties and advises against using them. He gave a justification, but I'm not sure I get it. Can somebody tell me why I should use properties and why I shouldn't? Does this change in C# 3.0 with automated properties?
I included Jeffrey Richter's thoughts as a reference:
• Field access is always accessible and writable, regardless of whether a property is read-only or write-only. It's recommended to provide both get and set accessor methods when defining a property.
• While a property method may throw an exception, field access does not.
• A field can be supplied as an out or ref parameter to a method, but not a property. The following code, for example, will not compile:
using System;
public sealed class SomeType
{
private static String Name
{
get { return null; }
set {}
}
static void MethodWithOutParam(out String n) { n = null; }
public static void Main()
{
// For the line of code below, the C# compiler emits the following:
// error CS0206: A property or indexer may not
// be passed as an out or ref parameter
MethodWithOutParam(out Name);
}
}
• While a property method can take a long time to perform, field access is always instantaneous. A common purpose for using properties is to execute thread synchronisation, which can cause the thread to hang indefinitely; consequently, if thread synchronisation is required, a property should not be used. In this case, a method is preferable. Calling the property method will be very slow if your class can be accessed remotely (for example, if your class is derived from System.MashalByRefObject), hence a method is preferable over a property. Classes derived from MarshalByRefObject, in my opinion, should never use properties.
• If a property method is called numerous times in a row, it may return a different value each time; a field always returns the same value. The System is in place. The readonly Now field of the DateTime class returns the current date and time. This property will return a different value each time you query it. This is an error, and Microsoft thinks they could correct it by making Now a method rather than a property in the class.
• A property method may have visible side effects, whereas field access does not. In other words, a user of a type should be able to change the order in which certain attributes described by the type are changed without causing the type to behave differently.
• A property method may use more memory or return a reference to something that isn't part of the object's state, thus changing the returned object has no effect on the original; querying a field always returns a reference to an object that is guaranteed to be part of the original object's state. Working with a property that returns a copy can be perplexing for developers, and this feature is often overlooked.