Reputation: 16703
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
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
Reputation: 941545
You are doing the work that the compiler does. Advantages of the Property keyword:
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
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
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