Flash
Flash

Reputation: 16703

What are the advantages of the Property keyword in VB.NET over using a Private field with getters and setters?

In VB.NET, what are the advantages of using the Property keyword rather than:

Private MyProperty as String
Public Sub setP(ByVal s as String)
    MyProperty = s
End Function
Public Function getP() as String
    return MyProperty
End Function

Coming from Java I tend to use this style rather than Property...End Property - is there any reason not to?

Upvotes: 4

Views: 2130

Answers (4)

Stefan
Stefan

Reputation: 11509

Using Properties makes the visual studio editor able to show/edit it in the property grid. If you are creating a control or dll that other will use they are used to be able to change design-time properties in the property-grid.

Also the property-grid-control will be able to pick that up if you add the control to the form and then set the SelectedObject-property of the grid to an instance of your class/control.

Upvotes: 2

Hans Passant
Hans Passant

Reputation: 941545

You are doing the work that the compiler does. Advantages of the Property keyword:

  • You can't accidentally mix up the getter and setter property type, a real issue in VB
  • No need for the awkward get and set prefixes, the compiler figures out which one you want
  • Data binding requires a property
  • You can take advantage of the auto property syntax, no need to declare the private field and only a single line of code.

The same declaration in VS2010 using the auto property syntax:

Public Property P As String

The compiler auto-generates the getter and setter methods and the private backing field. You refactor the accessors when necessary.

Upvotes: 10

chrissie1
chrissie1

Reputation: 5029

You will get some added benefits from properties that you will not get from using getters and setters.

Like reflection will find all your properties easily because there are methods for that.

ORM's for instance will easily be able to find your properties but it will be harder for them to find the getters setters because the convention is to use the properties.

So functionally they might be the same but the convention is to use properties.

Upvotes: 4

Phil Murray
Phil Murray

Reputation: 6554

Functionally there is no difference but for me the usage of Properties is a cleaner implementation. Look here

.Net 4 also gives AutoImplement proeprties to VB.net here wher ethe private backing variable is automatically created by the compiler resulting in much cleaner code and less boiler plate code to write.

Upvotes: 2

Related Questions