tags:

views:

158

answers:

6

Possible Duplicates:
Should I use public properties and private fields or public fields for data?
Property(with no extra processing) vs public field

What is the point in having a property inside a class that simply get and sets a member variable?

What practical difference would be there to just making the variable public?

+3  A: 

Ease of maintenance... you can log assignments, add validation, etc., without breaking existing callers.

Ben Voigt
+5  A: 

I think similar questions have been answered on many occasions, but basically it gives you the option of adding error checking/etc validation to your property without changing the public interface.

There's also some good information here, the following quote probably answers your question best:

A property communicates the idea of "I will make a value available to you, or accept a value from you." It's not an implementation concept, it's an interface concept. A field, on the other hand, communicates the implementation - it says "this type represents a value in this very specific way". There's no encapsulation, it's the bare storage format. This is part of the reason fields aren't part of interfaces - they don't belong there, as they talk about how something is achieved rather than what is achieved.

R0MANARMY
+2  A: 

You can't databind to public variables. Only public properties.

Keltex
Is this also the case for some data bindings in WinForms?
Craig Johnston
I *believe* that data binding in WinForms can only come from data sources like databases. If you want to simulate this, you can have the `set` property change the object, and the `Changed` event of the object change the property. This way, you can just use the setter and not worry about updating your gui everywhere.
Daniel Rasmussen
A: 

Properties allow future expansion in accessors and getters (validation, eventing, etc).

You can also make a property virtual, whereas a field cannot be.

The IL for calling fields is different to that of properties, so if you change a field to a property later on, existing compiled calling code will break.

Drew Noakes
+1  A: 

If you ever want to change the way the method is accessed, just changing the property is much easier than going through all of your code to find it. Also, you could make the property virtual, change the underlying data type easily, or use a Settings variable so that it's saved and recalled automatically. I had a similar question myself.

Daniel Rasmussen
A: 

The point is that caller of your class do not know what field the property gets/sets, whether it's calculated, fetched from somewhere, or whether messing with it causes and update/change to the state of you class instance. With a simple field call none of these are an option.

filip-fku