views:

40

answers:

2

Hi guys,

What are the benefits of defining a property for a object instead of giving direct access to the private variable?

Instead of :

public class A

    private _x as integer = 0

    Public property X() as integer
        Get
            return _x

        End Get
        Set(ByVal value As integer)
            _x = value
        End Set
    End Property

end class

Why we can't do following:

public class A

    public _x as integer = 0

end class

What are the benefits?

+1  A: 

The main reason is that you can add behavior (logging, validation, database backend, etc.) to the property later without changing the ABI (Application Binary Interface). If you had defined it as a field, then wanted to add behavior, you would need to change to a property (or a method). Either of these would require other code to be recompiled (and modified, if you went the method route).

Matthew Flaschen
+5  A: 

One benefit is that a number of frameworks look for properties of a class for binding purposes, not fields. So directly exposing the _x field will cause some headaches when you're wondering why a framework isn't setting the value as you might expect.

Also due to encapsulation you can change what happens when calling code interacts with the field. Hiding the field behind a property getter/setter allows you to perform additional actions like triggering when the value changes, updating other internal state, or changing the implementation entirely so it's just a wrapping call to a child object.

Agent_9191
+1 This is one of the points where VB6 was arguably better than .Net. In VB6, a directly exposed field behaves exactly like a property. If you need to add behaviour later, you can change your field to a property and nothing breaks. This difference between fields and properties is why we have the clunky automatically-implemented properties.
MarkJ