Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I avoid using Properties in C#?

Tags:

c#

properties

In his excellent book, CLR Via C#, Jeffrey Richter said that he doesn't like properties, and recommends not to use them. He gave some reason, but I don't really understand. Can anyone explain to me why I should or should not use properties? In C# 3.0, with automatic properties, does this change?

As a reference, I added Jeffrey Richter's opinions:

• A property may be read-only or write-only; field access is always readable and writable. If you define a property, it is best to offer both get and set accessor methods.

• A property method may throw an exception; field access never throws an exception.

• A property cannot be passed as an out or ref parameter to a method; a field can. For example, the following code 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);    } } 

• A property method can take a long time to execute; field access always completes immediately. A common reason to use properties is to perform thread synchronization, which can stop the thread forever, and therefore, a property should not be used if thread synchronization is required. In that situation, a method is preferred. Also, if your class can be accessed remotely (for example, your class is derived from System.MashalByRefObject), calling the property method will be very slow, and therefore, a method is preferred to a property. In my opinion, classes derived from MarshalByRefObject should never use properties.

• If called multiple times in a row, a property method may return a different value each time; a field returns the same value each time. The System.DateTime class has a readonly Now property that returns the current date and time. Each time you query this property, it will return a different value. This is a mistake, and Microsoft wishes that they could fix the class by making Now a method instead of a property.

• A property method may cause observable side effects; field access never does. In other words, a user of a type should be able to set various properties defined by a type in any order he or she chooses without noticing any different behavior in the type.

• A property method may require additional memory or return a reference to something that is not actually part of the object's state, so modifying the returned object has no effect on the original object; 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 very confusing to developers, and this characteristic is frequently not documented.

like image 550
Quan Mai Avatar asked Mar 29 '09 14:03

Quan Mai


People also ask

Should I always use properties?

When should I use a property? In general, you should use properties if you need them to look and behave like a variable. Properties give you a level of abstraction to change the fields while not affecting how a class uses them.

Should I use fields or properties?

You want to use properties over fields becuase, when you use properties you can use events with them, so in a case when you want to do some action when a property changes, you can bind some handlers to PropertyChanging or PropertyChanged events. In case of fields this is not possible.

When should you use properties?

Consider using a property if the member represents a logical attribute of the type. Do use a property, rather than a method, if the value of the property is stored in the process memory and the property would just provide access to the value.

Why we use properties in C# instead of fields?

Using properties has a couple of distinct advantages: It allows for versioning if later you need extra logic. Adding logic to the getter or setter won't break existing code. It allows data binding to work properly (most data binding frameworks don't work with fields).


1 Answers

Jeff's reason for disliking properties is because they look like fields - so developers who don't understand the difference will treat them as if they're fields, assuming that they'll be cheap to execute etc.

Personally I disagree with him on this particular point - I find properties make the client code much simpler to read than the equivalent method calls. I agree that developers need to know that properties are basically methods in disguise - but I think that educating developers about that is better than making code harder to read using methods. (In particular, having seen Java code with several getters and setters being called in the same statement, I know that the equivalent C# code would be a lot simpler to read. The Law of Demeter is all very well in theory, but sometimes foo.Name.Length really is the right thing to use...)

(And no, automatically implemented properties don't really change any of this.)

This is slightly like the arguments against using extension methods - I can understand the reasoning, but the practical benefit (when used sparingly) outweighs the downside in my view.

like image 144
Jon Skeet Avatar answered Oct 07 '22 10:10

Jon Skeet