Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

c# - When to use properties instead of functions

This is probably a matter of personal preference, but when do you use properties instead of functions in your code

For instance to get an error log I could say

string GetErrorLog()
{
      return m_ErrorLog;
}

or I could

string ErrorLog
{
     get { return m_ErrorLog; }
}

How do you decide which one to use? I seem to be inconsistent in my usage and I'm looking for a good general rule of thumb. Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I tend to use properties if the following are true:

  • The property will return a single, logic value
  • Little or no logic is involved (typically just return a value, or do a small check/return value)

I tend to use methods if the following are true:

  • There is going to be significant work involved in returning the value - ie: it'll get fetched from a DB, or something that may take "time"
  • There is quite a bit of logic involved, either in getting or setting the value

In addition, I'd recommend looking at Microsoft's Design Guidelines for Property Usage. They suggest:

Use a property when the member is a logical data member.

Use a method when:

  • The operation is a conversion, such as Object.ToString.
  • The operation is expensive enough that you want to communicate to the user that they should consider caching the result.
  • Obtaining a property value using the get accessor would have an observable side effect.
  • Calling the member twice in succession produces different results.
  • The order of execution is important. Note that a type's properties should be able to be set and retrieved in any order.
  • The member is static but returns a value that can be changed.
  • The member returns an array. Properties that return arrays can be very misleading. Usually it is necessary to return a copy of the internal array so that the user cannot change internal state. This, coupled with the fact that a user can easily assume it is an indexed property, leads to inefficient code. In the following code example, each call to the Methods property creates a copy of the array. As a result, 2n+1 copies of the array will be created in the following loop.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...