One important aim of many object-oriented programming languages is to allow you to encapsulate internal details in a class. Visual Basic .NET or Visual Basic 2005 allows you to define properties to provide controlled access to internal details in a class. This article describes how you can define and use properties in a Visual Basic .NET or Visual Basic 2005 application.
A property can be read-only, write-only, or read-write. A Get accessor provides read access, and a Set accessor provides write access. You can add code to these accessors to provide the appropriate functionality to get or set the property.
In this article, you create a class named Employee. Within this class, you define a read-write property for the name of the employee, a property to read the salary of the employee, and a property to calculate how long the employee has worked for the company. You then create an Employee object in your application and use its properties.
Add the following code to add a read-write property named FullName. The Get accessor returns the name of the employee. The Set accessor uses the Value parameter that is passed into the Set accessor to set the name of the employee.
Public Property FullName() As String Get Return Me.Name End Get Set(ByVal Value As String) Me.Name = Value End SetEnd Property
Add the following code to add a read-only property named Remuneration. The Get accessor returns the salary of the employee. There is no Set accessor because the salary cannot be set directly; the only way to change the salary is to call the PayRise method.
Public ReadOnly Property Remuneration() As Decimal Get Return Me.Salary End GetEnd Property
Add the following code to add another read-only property named DaysSinceJoined. The Get accessor calculates how many days the employee has worked for the company.
Public ReadOnly Property DaysSinceJoined() As Integer Get Dim timespan As TimeSpan = DateTime.Now.Subtract(Me.HireDate) return timespan.Days End GetEnd Property
The application displays the following information in the console (the "Days since joined" value depends on the current date):
Full name: Jayne LafayetteRemuneration: 125000Days since joined: 1139
Return to the Module1.vb file in the Code View window, and add the following code at the end of your Main method:
worker.Remuneration = 1000000
Try to build the application. You receive a compilation error because Remuneration is a read-only property.
Change the statement as follows:
worker.Salary = 1000000
Try to build the application again. You receive another compilation error because the Salary field is marked as Private. The only way to modify the salary of the employee is to use the Public PayRise method.