Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 901
Flash Avatar asked Dec 03 '22 02:12

Flash


1 Answers

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.

like image 124
Hans Passant Avatar answered Dec 04 '22 16:12

Hans Passant