This documentation is archived and is not being maintained.

Accessing Default Members

Any type can have a default member, which is a member that is invoked when no member name is given. You can invoke default members by calling the Type.InvokeMember method with String.Empty ("") as the member name. InvokeMember retrieves the System.Reflection.DefaultMemberAttribute attribute from the type and then invokes it. The following example invokes the default member of Class1, and the value it returns is assigned to o.

Dim c As New Class1()
Dim o As Object
o = c.GetType().InvokeMember("", BindingFlags.InvokeMethod, Nothing, c, New Object(){})
Console.WriteLine("Default member result: {0}", o)

Default members are indicated by the DefaultMemberAttribute attribute on the declaring type. The class shown in the following example has the DefaultMemberAttribute manually added. Do not add the DefaultMemberAttribute manually if the class has an indexer declared; in that case, the compiler automatically adds the attribute.

<DefaultMember("GetIVal")> _
Public Class Class1
    Private ival As Integer
    Private sval As String

    Public Sub New()
        ival = 5050
        sval = "6040"
    End Sub

    Public Function GetIVal() As Integer
        Return ival
    End Function

    Public Function GetSVal() As String
        Return sval
    End Function
End Class

The following example shows how to retrieve the default member by retrieving the custom attribute for the default member.

Dim classType As Type = GetType(Class1)
Dim attribType As Type = GetType(DefaultMemberAttribute)
Dim defMem As DefaultMemberAttribute = _
    CType(Attribute.GetCustomAttribute(CType(classType, MemberInfo), attribType), _
Dim memInfo() As MemberInfo = classType.GetMember(defMem.MemberName)

It might be simpler to use the Type.GetDefaultMembers method, which produces the same result. However, GetDefaultMembers throws an InvalidOperationException if more than one default member is defined on the type. The following example shows the syntax for GetDefaultMembers.

Dim t As Type = GetType(Class1)
Dim memInfo() As MemberInfo = t.GetDefaultMembers()

You can also get the custom attributes for a type and select just the DefaultMemberAttribute, by using the GetCustomAttributes method. The following example demonstrates this technique.

Dim t As Type = GetType(Class1)
Dim customAttribs() As Object _
    = t.GetCustomAttributes(GetType(DefaultMemberAttribute), False)
If customAttribs.Length > 0 Then
    Dim defMem As DefaultMemberAttribute = CType(customAttribs(0), DefaultMemberAttribute)
    Dim memInfo() As MemberInfo = t.GetMember(defMem.MemberName)
    If memInfo.Length > 0 Then
        Console.WriteLine("Default Member: {0}", memInfo(0).Name)
    End If
End If