Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET - When should I use a property vs. variable + accessor function?

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?

like image 449
Brian Webster Avatar asked Nov 02 '09 21:11

Brian Webster


People also ask

Why do we use properties instead of variables in C#?

Use of properties makes your code more object oriented. By making member variables public, you are exposing your implementation.

When should you use properties C#?

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.

What is the difference between property and variable in C#?

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.


1 Answers

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:

  • 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.

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).

like image 135
Reed Copsey Avatar answered Sep 30 '22 15:09

Reed Copsey