Assigning objects

We have been assigning values to variables and properties throughout the course. It turns out you can assign complete objects to object variables of the same class. We will illustrate this with the Font class.

In printing, a font is a complete set of type of one size and face. The size is measured in points where a point is approximately 1/72 of an inch. The faces have family names like "Times New Roman" or "Microsoft Sans Serif", and each letter shape is carefully designed for beauty and readability.

VB.NET includes a Font class. Three of the properties of a Font are Size, Family, and FontStyle (Regular, Bold, Italic, etc.), and these are initialized when a new font is constructed. This is illustrated by the greeting program listed below:

Private Sub btnBig_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBig.Click
   Dim bigFont As Font
   bigFont = New Font("microsoft sans serif", 28)
   lblGreet.Font = bigFont
   lblGreet.Text = "Hello my friend!"
End Sub

Private Sub btnSmall_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSmall.Click
   Dim smallFont As Font
   smallFont = New Font("microsoft sans serif", 14)
   lblGreet.Font = smallFont
   lblGreet.Text = "Hello my friend!"
End Sub
The event handlers each declare and then construct a Font. Both have the same Family microsoft sans serif, but the bigFont has a Size of 28 and smallFont has a Size of 14.

The Font is then assigned to the Font property of lblGreet, and the appropriate greeting is displayed.

Since I did not specify a value for the FontStyle property in either cases, the default value of Regular is used.

Note that in this listing, I separated declaration and construction into two statements, but I could have also combined them as follows:

Private Sub btnBig_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBig.Click
   Dim bigFont As Font= New Font("microsoft sans serif", 28)
   lblGreet.Font = bigFont
   lblGreet.Text = "Hello my friend!"
End Sub

Private Sub btnSmall_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSmall.Click
   Dim smallFont As Font = New Font("microsoft sans serif", 14)
   lblGreet.Font = smallFont
   lblGreet.Text = "Hello my friend!"
End Sub

We used this combined declare/construct statement in the Random class example because the separate, two statement format can only be used inside a subprogram.


Disclaimer: The views and opinions expressed on unofficial pages of California State University, Dominguez Hills faculty, staff or students are strictly those of the page authors. The content of these pages has not been reviewed or approved by California State University, Dominguez Hills.