0

I see we can define properties in two way in VB.NET.

As below

 Private newPropertyValue As String
    Public Property ID() As String
        Get
            Return newPropertyValue
        End Get
        Set(ByVal value As String)
            newPropertyValue = value
        End Set
    End Property

Or as below in one line

Public Property ID As String

Is there any difference or later is an improved way to define properties.

Matt Wilko
  • 26,994
  • 10
  • 93
  • 143
user2739418
  • 1,623
  • 5
  • 29
  • 51
  • 2
    You start with the bottom one. And then some day you'll switch to the top one because you need to put more code in the accessors, usually the Set() – Hans Passant Jul 08 '15 at 08:27

2 Answers2

1

If you just want basic accessors use the shorthand, it sets everything up for you and is easier to read in my opinion.

However you will need to use the standard syntax if you want to:

  • Include any extra processing such as validation.
  • Have different accessibility for each accessor (private get, public set)
  • Use write or read only properties

Plenty of extra info here as well: https://msdn.microsoft.com/en-us/library/dd293589.aspx

user3510227
  • 576
  • 2
  • 6
0

The second format is called an Auto-Implemented property. Is is just shorthand for the first option. If you don't need any logic or additional code when getting or setting a property you can use this.

You can access the backing field of an auto implemented property using the name:

_[PropertName]

But I would advise against this.

When you need some code or logic in your property you have to use the first option.

Currently (VS2013) if you want a read-only or write-only property then you have to use the longhand version. In VS2015 you can use auto implemented properties for these as well.

Matt Wilko
  • 26,994
  • 10
  • 93
  • 143