Export (0) Print
Expand All
This topic has not yet been rated - Rate this topic

Accessing Default Members

Any type can have a default member, which is a member that is invoked when no member name is given. The following Visual Basic example invokes the default member of Class1, and the value it returns is assigned to i.

Dim c As New Class1()
Dim i As Integer i = Convert.ToInt32(c)

Default members are marked with the System.Reflection.DefaultMemberAttribute. attribute. The following example shows how to retrieve the default member by retrieving the custom attribute for the default member.

Dim t As Type = GetType(DefaultMemberAttribute)
Dim defMem As DefaultMemberAttribute = CType(Attribute.GetCustomAttribute([Assembly].GetAssembly(t), t), DefaultMemberAttribute)
Dim memInfo As MemberInfo() = t.GetMember(defMem.MemberName)

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

Dim memInfo As MemberInfo() = t.GetDefaultMembers()

You can invoke default members by calling Type.InvokeMember with String.Empty ("") as the member name. InvokeMember retrieves the member with DefaultMemberAttribute from the type and then invokes it.

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.