The Default Property

Objects can implement a default property if desired. A default property can be used to simplify the use of our object at times, by making it appear as if our object has a native value. A good example" of this behavior is the Collection object, which has a default property called Item that returns die value of a specific item, allowing us to write code similar to:

Dim colData As New Collection () Return ColData(Index)

Default properties must be parameterized properties. A property without a parameter cannot be marked as the default. This is a change from previous versions of VB, where any property could be marked as the default.

Our Person class has a parameterized property – the Phone property we built earlier. We can make this the default property by using the Default keyword:

Default Public Property Phone(ByVal Location As String) As String
Get
Return colphones.Item(Location)
End Get
Set(ByVal Value As String)
If colPhones.ContainsKey(Location) Then
CoPhones.Item(ocation) = Value
End If
End Set
End Property

Prior to this change, we would need code such as the following to use the phone property:

Dim myPerson As New person()
MyPerson.Phonefhome") = "555-1234′

But now, with the property marked as Default, we can simplify our code:

Myperson("home") ="555-1234"

By picking appropriate default properties, we can potentially make the use of our objects more intuitive.

It's very calm over here, why not leave a comment?

Leave a Reply