Default Properties

A property that accepts arguments can be declared as the default property for a class. A default property is the property that Visual Basic will use when no specific property has been named for an object. Default properties are useful because they allow you to make your source code more compact by omitting frequently used property names.

The best candidates for default properties are those properties that accept parameters and that you think will be used the most often. For example, the Item property is a good choice for the default property of a collection class because it is used frequently.

The following rules apply to default properties:

  • A type can have only one default property, including properties inherited from a base class. There is one exception to this rule. A default property defined in a base class can be shadowed by another default property in a derived class.

  • If a default property from a base class is shadowed by a non-default property in a derived class, the default property is still accessible using default property syntax.

  • A default property may not be Shared or Private.

  • If an overloaded property is a default property, all overloaded properties with that same name must also specify Default.

  • Default properties must accept at least one argument.


The following example declares a property that contains an array of strings as the default property for a class:

Class Class2
    ' Define a local variable to store the property value. 
    Private PropertyValues As String()
    ' Define the default property. 
    Default Public Property Prop1(ByVal Index As Integer) As String 
            Return PropertyValues(Index)
        End Get 
        Set(ByVal Value As String)
            If PropertyValues Is Nothing Then 
                ' The array contains Nothing when first accessed. 
                ReDim PropertyValues(0)
                ' Re-dimension the array to hold the new element. 
                ReDim Preserve PropertyValues(UBound(PropertyValues) + 1)
            End If
            PropertyValues(Index) = Value
        End Set 
    End Property 
End Class

Accessing Default Properties

You can access default properties using abbreviated syntax. For example, the following code fragment uses both standard and default property syntax:

Dim C As New Class2
' The first two lines of code access a property the standard way. 

' Property assignment.
C.Prop1(0) = "Value One" 
' Property retrieval.

' The following two lines of code use default property syntax. 

' Property assignment.
C(1) = "Value Two" 
' Property retrieval.

See Also


Upgrade Recommendation: Resolve Parameterless Default Properties

Default Property Changes for Visual Basic 6.0 Users


Default (Visual Basic)