Array Class Collections File String Console Data Directive Enum Exception If Interface Lambda Loop Nothing Number Process Property Regex Sort StringBuilder Structure Sub Time Windows
A property has a getter and a setter. It is a layer of abstraction on a value. This value is called a backing store. The Property keyword decorates a member similar to a Function. With Get it returns a value. With Set it stores a value.
This example program uses the Property keyword. On the Number() property, we provide a Get block and a Set block. In Get we return a value—the backing store _count. In Set we receive a parameter and then store it in the _count field.
Types:A VB.NET property can have any data type.
It does not need to be an Integer.
And:Additional logic can be inserted in either Get or Set. In fact this extra layer of indirection is often used to validate arguments.
Program that uses property syntax: VB.NET Class Example Private _count As Integer Public Property Number() As Integer Get Return _count End Get Set(ByVal value As Integer) _count = value End Set End Property End Class Module Module1 Sub Main() Dim e As Example = New Example() ' Set property. e.Number = 1 ' Get property. Console.WriteLine(e.Number) End Sub End Module Output 1
When the value 1 is assigned to the Number property, Set is executed. The _count field stores the value 1. When the Number property is accessed but not assigned to, Get is executed. The value of the _count field is returned.
Tip:A property must have both Get and Set members. It is possible to use the ReadOnly or WriteOnly keywords to eliminate this requirement.
Some properties in the .NET Framework are not meant to be assigned. For example the Count property on collections is not mutable. In VB.NET the ReadOnly modifier changes the Property type to only have a Get method.
Program that uses ReadOnly Property: VB.NET Class Example Public ReadOnly Property Count() As Integer Get Return 500 End Get End Property End Class Module Module1 Sub Main() Dim e As Example = New Example() Console.WriteLine(e.Count) End Sub End Module Output 500
In this program, the Count() property returns a constant Integer. But Get could perform any calculation and return the value of a field. ReadOnly does not require a constant return value.
Caution:If we try to assign a value to Count, we get this error: "Property Count is ReadOnly." So don't do that.
Properties simplify syntax of VB.NET programs. And they provide a facility in the language that enforces consistency. Instead of writing custom getters and setters, we use properties.
And:This makes VB.NET programs easier to read.
It makes them easier to understand.