user7661499
user7661499

Reputation:

Full private property for setter and getter

I would like to make my property fully private (get and set) if so is it better to just use private variable instead of property or use private property itself?

EDIT (for further questions)

'ok i can use _foo within class and Foo in outside classes
Private _foo As String
Private Property Foo() As String
    Get
        Return _foo
    End Get
    Set(value As String)
        _foo = value
    End Set
End Property

'issue as cannot use _name with class
Property Name as String

'it's ok i can use _age within class but looks not good as e.g above Name... without undescore..
Private _age as Integer

Upvotes: 1

Views: 336

Answers (1)

Bugs
Bugs

Reputation: 4489

There is no real difference between:

Private _foo As String
Private Property Foo() As String
    Get
        Return _foo
    End Get
    Set(value As String)
        _foo = value
    End Set
End Property

And:

Private Foo As String

The keyword Private keeps it within the scope of the class. That's all. You now can't access Foo in either context from anywhere other than where it was declared.

There are a couple of advantages to using a Property however. For one, you can make a property ReadOnly for access:

Private _foo As String
Public ReadOnly Property Foo() As String
    Get
        Return _foo
    End Get
End Property

This allows for access outside of the class it originates from. You can do all the setting on _foo within the originating class without worrying about this being changed outside the class.

Another advantage to a Property is you can raise events and/or log changes:

Private _foo As String
Public Property Foo() As String
    Get
        Return _foo
    End Get
    Set(value As String)
        If Not (value = _foo) Then
            _foo = value
            NotifyPropertyChanged()
        End If
    End Set
End Property

You can also validate the value being set and/or update other private fields:

Private _foo As Integer
Public WriteOnly Property Foo() As Integer
    Set(value As Integer)
        _foo = value
        If _foo > 10 Then
            _bar = True
        End If
    End Set
End Property

Private _bar As Boolean
Public ReadOnly Property Bar() As Boolean
    Get
        Return _bar
    End Get
End Property

A Property can also be used for DataBinding whilst a field cannot.

I'm sure there are other differences however this should give you a good indication as to whether you require the use of a Property or whether a field is good enough.

Upvotes: 2

Related Questions