3

I've been using classes for a while now, but I feel I may have been using them incorrectly.

When I create the properties for the class, I just use public variables so I end up with something like the following:

Class clsMyClass
    Public Name As String
End Class

However, I've been reading some info on the net and they suggest that it should be set up in the following way:

Class clsMyClass
    Private Name As String

    Property UsersName() As String
        Get
            Return Name
        End Get
        Set(ByVal Value As String)
            Name = Value
        End Set
    End Property
End Class

Is the way I'm doing it extremely incorrect? If so, why? I feel like the second method adds some sort of security but to be honest, it just looks like unnecessary code..?

Ant Moore
  • 123
  • 1
  • 12
  • [Good to read article](http://stackoverflow.com/questions/295104/what-is-the-difference-between-a-field-and-a-property-in-c). C#, but the principle applies to VB.NET as well. Also [this](http://stackoverflow.com/questions/3069901/properties-vs-fields-need-help-grasping-the-uses-of-properties-over-fields) and [this](http://stackoverflow.com/questions/653536/difference-between-property-and-field-in-c-sharp-3-0). – Victor Zakharov Dec 16 '13 at 00:51

4 Answers4

3

One advantage of properties is that they let you customise the access to your private fields and enable you to do more so you can do the following (examples, it's not limited to that):

  • Make a property read-only for public access
  • Raise an even when a property is updated
  • Update other private fields when a property is updated
  • Validate the value that is being set
Szymon
  • 42,577
  • 16
  • 96
  • 114
2

See below advantages of Properties over Variables from the C# in Depth article:

• There's more fine-grained access control with properties. Need it to be publicly gettable but really only want it set with protected access? No problem (from C# 2 onwards, at least).

• Want to break into the debugger whenever the value changes? Just add a breakpoint in the setter.

• Want to log all access? Just add logging to the getter.

• Properties are used for data binding; fields aren't.

Few other points: 1) You can also make properties read-only so no one from outside the class set the values but can fetch it. 2) You can do certain actions in the get and set. i.e. Append a prefix anytime set is called
3) You can also use auto-implemented property to minimize code like below:

Public Property Name As String 
Adarsh Shah
  • 6,755
  • 2
  • 25
  • 39
0

You are not doing anything wrong. Properties give you a shorthand basically, a syntactic sugar.

You can still use a backing private variable and do logic in get and set if you have to while using properties. Even better is the private/protected set or get, which is again another syntactic sugar so that you won't have to write all the code manually.

AD.Net
  • 13,352
  • 2
  • 28
  • 47
0

First of all, VB.NET allows you to use this syntax (called shorthand property declaration - I believe since VS 2010):

Public Property Name As String

Not so much different from this (called field declaration):

Public Name As String

Second, Microsoft data binding does not work well with fields. Try this example (see below).

Example. Put a listbox called ListBox1 (default name) and a button called Button1 on an empty form in an empty WinForms project. Replace your form code with this:

Public Class Form1
  Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim lst As New List(Of clsMyClass)
    lst.Add(New clsMyClass)
    ListBox1.ValueMember = "Name"
    ListBox1.DisplayMember = "Name"
    ListBox1.DataSource = lst
  End Sub
End Class

Class clsMyClass
  Public Property Name As String = "Hello"
End Class

Start the application and notice that a listbox is populated with one entry, Hello. This proves that binding worked correctly. Now replace your property declaration with a field declaration instead. Start your application one more time and notice that a listbox is showing your class type converted to String. It means that your field binding did not work, and default binding was used instead, where DisplayMember is assigned sort of classInstance.ToString().

If you are curious to learn more about what happens behind the scenes, you can put a breakpoint on .DataSource assignment, and see how DisplayMember gets reset or keeps its value depending on whether you are using fields or properties.

Victor Zakharov
  • 25,801
  • 18
  • 85
  • 151
  • Not quite. In VS2012, at any rate, `Public Property Name As String` creates an implicit backing field, `_Name As String`. Not so with `Public Name As String` - that is just a public field. The former is called (in intellisense) an implicitly declared property...trying to also create your own `_Name` throws an error. The backing field is not shown, but you can reference it and Shift-F2 takes you to the implicit Property definition. **Functionally** they are not too different though...good to know about the databinding! – Ňɏssa Pøngjǣrdenlarp Dec 16 '13 at 00:39
  • @Plutonix: Are you trying to say that non-working data binding compared to working data binding is no functional difference? I know what you are saying, just trying not to get into too much technical detail, the OP is clearly starting his way through. It's important not to pick the wrong path here. – Victor Zakharov Dec 16 '13 at 00:48