Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use a property vs a method? [duplicate]

Tags:

c#

.net

oop

Possible Duplicate:
Properties vs Methods

Is there any rule or general best practice as to when to use a property vs a method? Technically any parameterless method can be made in a property and any property can be made a method, but sometimes when to decide when to use one of the other can be blurred.

I was hoping to get some rules you guys kept in mind when deciding between the two.

like image 385
jdelator Avatar asked Dec 06 '09 04:12

jdelator


1 Answers

To add to what cletus has said.

This is from msdn: "Property Usage Guidelines" http://msdn.microsoft.com/en-us/library/bzwdh01d(VS.71).aspx See the "Properties vs. Methods" section:

  • 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.
like image 168
brian chandley Avatar answered Sep 18 '22 17:09

brian chandley