I have the following class:
Class MyClass
Property MyInteger as Integer
Set(ByVal value as Integer)
_MyInteger = value
End Set
Get
Return _MyInteger
End Get
End Property
Private _MyInteger as Integer
End Class
As I’m not using any validation etc in my Property, is there any advantage of using a Property in this case, or would it be neater to use:
Class MyClass
Public MyInteger as Integer
End Class
Generally speaking, public member variables in classes are frowned upon, it breaks the encapsulation tenet of object oriented programming.
Such rules are not there for the sake of it, but for good reason. By making the variable public you are making the code more difficult to maintain and restricting what you can do with it later.
Although you may not want to do validation on the value now, what happens if you need to add it later? What about if you need to make it a read only value, where the class itself can change the value, but clients cannot?
Where this causes the biggest problem is if you are implementing a library. If you supply version 1 of the library with a public member and then in the second version of the library, have to convert it to a property, you will have to recompile every assembly which uses that library.
It is for this reason (amongst others) that VB.net 10 added auto properties:
Now you can default to creating auto-properties for things which you would have made public member variables, then if you later need to upgrade to a full property, so can do so without changing the interface.