views:

495

answers:

11

For private class variables, which one is preferred?

If you have a property like int limit, you want it to be:

int Limit {get; set;}

and use it inside the class, like so:

this.Limit

Is there a reason to use it or not use it? Maybe for performance reasons?

I wonder if this is a good practice.

+13  A: 

For a private member, I only make it a property when getting and/or setting the value should cause something else to occur, like:

private int Limit
{
   get
   {
       EnsureValue();
       return this._limit;
   }
}

Otherwise, fields are fine. If you need to increase their accessibility, it's already a big enough change that making it a property at that point isn't a huge deal.

Edit: as Scott reminds us in the comments, side effects in properties can often cause more pain than anything else. Don't violate Single Responsibility and limit property logic to consistent, logical operations on the value only that must be done at the gate - such as lazy loading (as in the example above), transforming an internal structure into a publicly-useful format, etc.

Rex M
+1 - concise and includes code sample.
Chris Ballance
+1 I read your code and was WTF. After reading your post it became very clear the reasoning behind the code. Good Job.
Chuck Conway
You should actually try to avoid properties which have side effects. Properties are evaluated by all sorts of different things, including the debug watch, locals, and auto windows and the quick watch window. As a result, properties with side effects can cause lots of wierd behavior during debug sessions and can sometimes make finding a runtime error very difficult.
Scott Dorman
@Scott, determining what a "side effect" is might get into a lot of gray areas. For instance, what about raising a PropertyChangedNotification event? What about validating the value set into the property? What about lazy-loading the value from a database? What about doing change-tracking on the values set into the property? There are quite a lot of things that can be done here that are well beyond simply setting a value, but stop short of the classic "side-effect" issue.
Cylon Cat
+1  A: 

Granted, since it's a private API, its an implementation detail - you can do whatever you want here. However, there is very little reason to not use a property, even for private classes. The properties get inlined away by the JIT, unless there is extra code in place, so there isn't really a performance impact.

The biggest reasons to prefer properties, IMO, are:

  1. Consistency in your API - You'll want properties in publicly exposed APIs, so making them in the private API will make your programming exprience more consistent, which leads to less bugs due to better maintainability
  2. Easier to convert private class to public
Reed Copsey
+2  A: 

I would say its good practice to use a property. If ever you had to expose the limit value and used a local member it will require more coding while if its a property it would only require a change of its modifier.

I think it's cleaner also.

Pat
+6  A: 

The only real benefit an auto-property has over a field when the accessibility is private is that you can set a breakpoint on accesses and updates of the variable. If that is important to your scenario then definitely use an auto-property. Otherwise, given there is no substantial advantage, I choose to go with the simplest construct which is a field.

JaredPar
One thing you're missing here is the ability to make future modifications without changing the public interface. Properties give you a lot more flexibility in terms of public interface stability.
Cylon Cat
+1  A: 

There's nothing wrong with having private or protected properties; this is mostly useful when there are some rule or side effect associated with the underlying variable.

The reason why property seem more natural for public variables is that in the public case, it is a way to edge one's bet against future implementation changes, whereby the property will remain intact but the implementation details somehow move around (and/or some additional business rule will be needed).

On performance, this is typically insignificant, or indeed identical for straight-assignement properties.

I personally dislike (but often use) plain assignement properties because they just clutter the code. I wish C# would allow for "after the fact refactoring".

mjv
A: 

Properties are just syntactic sugar, C# will compile them into get_PropertyName and set_PropertyName, so performance differences are not a consideration.

Matt Briggs
The *get* and *set* for properties equate to method calls, hence properties are slower. So why say performance differences aren't a consideration?
NVRAM
because they aren't. millionth of a second differences don't matter in the slightest except for very specific types of situations. It is like saying you should use for instead of foreach for performance reasons (and that is a much bigger difference then method vs property access)
Matt Briggs
+1  A: 

The point of automatic properties is they are very quick at creating a public access to some field in your class. Now, they offer no benefit over exposing straight up fields to the outside world, other than one big one.

Your class' interface is how it communicates with the outside world. Using automatic properties over fields allows you to change the internals of your class down the road in case you need to make setting the value of that property do something or check authorization rules or something similar on the read.

The fact that you already have a property means you can change your implementation without breaking your public interface.

Therefore, if this is just a private field, an automatic property isn't really that useful, not only that, but you can't initialize public properties at declaration like you can with fields.

Nick
A: 

If your data member need only set and get logic then properties are very good and fast solution in C#

Davit Siradeghyan
+1  A: 

From my perspective, using properties in lieu of variables boils down to:

Pros

  • Can set a break point for debugging, as Jared mentioned,
  • Can cause side-effects, like Rex's EnsureValue(),
  • The get and set can have different access restrictions (public get, protected set),
  • Can be utilized in Property Editors,

Cons

  • Slower access, uses method calls.
  • Code bulk, harder to read (IMO).
  • More difficult to initialize, like requiring EnsureValue();

Not all of these apply to int Limit {get; set;} style properties.

NVRAM
A: 

I generally follow the following principle: If it's for strictly private use, use a field as it is faster.

If you decide that it should become public, protected or internal some day, it's not difficult to refactor to a property anyway, and with tools like ReSharper, it takes about 3 seconds to do so... :)

TigerShark
A: 

Properties provide some very good automatic features (like Json and Xml Serialization)

Fields do not.

Properties can also be a part of an Interface. If you decide to refactor later on... this might be something to consider too.

Jeremy Bell