Is there ever a situation where I should do the following in .NET instead of using a property with read/write capability?
private S as string
public function GetS() as string
return S
end function
public sub SetS(byval NewS as string)
S = NewS
end function
Do properties simply provide a more efficient way for doing the same thing?
Will properties be any slower than the above accessor functions in a high performance application?
Use of properties makes your code more object oriented. By making member variables public, you are exposing your implementation.
Properties enable a class to expose a public way of getting and setting values, while hiding implementation or verification code. A get property accessor is used to return the property value, and a set property accessor is used to assign a new value.
In C# any "variable" that has a getter and setter is referred to as a property. A variable has no getters and setters or so that is what the text books say. My programming instructor made us have getters and setters for almost every variable that we created in Java.
Properties, internally, are nothing but a pair of methods. They basically evaluate to a get and set accessor method.
You should use properties, unless the property is going to cause some unexpected, potentially long running side effect, or there is some other good reason to use a method.
For details, I suggest reading the Property Usage Guidelines on MSDN. In particular, use a method when:
Otherwise, I'd use a property. Brad Abram's blogged some other details, including good reasons why certain API functions use methods (mostly because they could cause cross-computer communication, which would fall into the "side effect" category).
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