Possible Duplicate:
Properties vs Methods
In method you can type some code and in properties too. For example I have a property Name. When class name changes I would like to get some data from database and change state of my object. I can add this code to set part of my property. Other solution is to change set part to private and add method called SetName and in this method add my code.
So what is the difference? When is the point when it's not good to put some code to getter / setter and when to create own method that is used to change my property and other parts of my class?
Ans: A property is a named attribute of an object. Properties define the characteristics of an object such as Size, Color etc. or sometimes the way in which it behaves. A method is an action that can be performed on objects.
Member variables or methods in a class or structures are called Fields. Properties are an extension of fields and are accessed using the same syntax. They use accessors through which the values of the private fields can be read, written or manipulated. Properties do not name the storage locations.
A class holds the methods and properties that are shared by all of the objects that are created from it. Although the objects share the same code, they can behave differently because they can have different values assigned to them.
Here is a good set of guidelines for when to use properties vs methods from Bill Wagner (fixed link)
Repeated calls to the setter (with the same value) should yield no difference from a single call.
The get should not return a reference to internal data structures (See item 23). A method could return a deep copy, and could avoid this issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With