Skip to Content
Programming Visual Basic .NET, Second Edition
book

Programming Visual Basic .NET, Second Edition

by Jesse Liberty
April 2003
Intermediate to advanced
560 pages
14h 4m
English
O'Reilly Media, Inc.
Content preview from Programming Visual Basic .NET, Second Edition

Indexers and the Default Property

Some classes contain their own internal collection. For example, you might write your own School class that would contain, as a private member variable, a collection of the Students enrolled in the school. You might then want to access the School class as if it were an array of Students. To do so, you would use the default property, which will allow you to write:

Dim joe As Student = mySchool(5)

accessing the sixth element in mySchool’s internal collection!

As another example, suppose you create a listbox control named myListBox that contains a list of strings stored in a one-dimensional array, a private member variable named myStrings. A listbox control contains member properties and methods in addition to its array of strings. However, it would be convenient to be able to access the listbox array with an index, just as if the listbox were an array. For example, such a property would permit statements like the following:

Dim theFirstString As String = myListBox(0)

You implement this with the default property. Each class can have one default property, designated with the Default keyword. It is common to use the property name Item for the default property, but that is not required.

You can retrieve the default property with or without the property name. The following two code lines both retrieve the default property (which in this case, is called Item); the first uses the name, the second doesn’t:

Dim theFirstString As String = myListBox.Item(0) Dim ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming Visual Basic .NET

Programming Visual Basic .NET

Dave Grundgeiger
VB.NET Language in a Nutshell, Second Edition

VB.NET Language in a Nutshell, Second Edition

Steven Roman PhD, Ron Petrusha, Paul Lomax

Publisher Resources

ISBN: 0596004389Supplemental ContentCatalog PageErrata