There are some .NET
libraries which use methods for accessing object data instead of getters i.e HttpWebResponse.GetResponseStream()
.
Also there are examples of accessing an stream by a property i.e HttpResponse.OutputStream
.
My question is when to use which form of access and why ?
See the FxCop rule: CA1024: Use properties where appropriate.
Good question. Although a property is little more than syntax sugar for a pair of get/set methods, there two should be used in different times.
Generally, you should use a property-style getter when:
Generally, you should use a getter method when:
In a sentence, if conceptually speaking the value needed is something the object HAS, use a property. If the value needed is the result of something the object DOES, use a method.
Good question. This article brings up a few good points. In general, I use methods when the computation is expensive and properties when computation is not expensive (i.e. a stored value is returned).
My opinion which, I'm sure, will get to -10 real fast, is that you should only use properties for serialization. In all other cases explicit method call is preferable because when you look at it, you know that a method with possible side effects is being invoked.
I guess the "correct" (tm) answer is that when all your method would do is return the value, it is ok to use getter/setter, but if there is any work to do, use a method.
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