tags:

views:

454

answers:

4

Do you think it's better to always make protected class members an auto-implemented protected property to keep isolation or make it protected field is enough?

protected bool test { get; set; }

or

protected bool test;
+5  A: 

Generally, you should use autoproperties - this allow you to easily add verification, or anything else you need later on. This is especially important if the protected member will be used by classes outside your assembly, as adding such code won't break your contract with them, whereas changing a field to a method or property will.

thecoop
+3  A: 

property, backed by a private field.

This question might be useful

Sam Holder
What's the actual advantage over a protected field?
Steven Sudit
the question you linked was mine too ^^
Vince
encapsulation for one, and the ability to break the debugger when it is accessed makes it useful too.
Sam Holder
One advantage is the ability to do property-change notification with, for example, INotifyPropertyChanged. In general, this approach (protected property backed by a private field) promotes encapsulation, i.e. information-hiding. Don't reveal implementation unless you have a good reason for doing so. (I'm assuming the question centers on protected properties because some inheritance is involved.)
JMD
To be frank, I don't run into many cases in my own code where I want a class to be inherited while exposing a protected value, but it's certainly realistic. While my immediate reaction is to wrap it in a property, a protected relationship is pretty intimate already so I wonder how much leverage wrapping it really buys you here. I guess I'd agree on wrapping, but I have to admit to mixed feeling here.
Steven Sudit
+2  A: 

The suggested practice is to make it a property. The signature changes depending on whether it's a field or a property, which can cause problems if you're crossing assemblies. If you make it a property to begin with, you'll never have this problem. (often later you want to add logic when the property is read or written.)

In C#, auto-implementing the property is so easy, there's no reason not to do it.

Also, it makes things more clear. If it is really meant to be used by the outside world as part of the functioning of the object, make it a property. Otherwise, a future programmer might wonder if you made a field protected instead of private by accident.

Patrick Karcher
ok, sounds clear to make properted property! Thanks all
Vince
A: 

You should never allow direct access to a member variable from outside your class. Either use an auto-generated property or a property with a backing field. If you allow direct access, it can lead to some really bad debugging headaches when multiple methods change that value in a derivation chain and you don't know which one is causing the bug.

Jeff Yates