Export (0) Print
Expand All
1 out of 1 rated this helpful - 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. 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.


Class1 c = new Class1();
object o;
o = c.GetType().InvokeMember("", BindingFlags.InvokeMethod, null, c, new object[0]);
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 int ival;
    private string sval;

    public Class1()
    {
        ival = 5050;
        sval = "6040";
    }

    public int GetIVal()
    {
        return ival;
    }

    public string GetSVal()
    {
        return sval;
    }
}


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


Type classType = typeof(Class1);
Type attribType = typeof(DefaultMemberAttribute);
DefaultMemberAttribute defMem =
    (DefaultMemberAttribute)Attribute.GetCustomAttribute((MemberInfo)classType, attribType);
MemberInfo[] memInfo = 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.


Type t = typeof(Class1);
MemberInfo[] memInfo = 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.


Type t = typeof(Class1);
object[] customAttribs = t.GetCustomAttributes(typeof(DefaultMemberAttribute), false);
if (customAttribs.Length > 0)
{
    DefaultMemberAttribute defMem = (DefaultMemberAttribute)customAttribs[0];
    MemberInfo[] memInfo = t.GetMember(defMem.MemberName);
    if (memInfo.Length > 0)
    {
        Console.WriteLine("Default Member: {0}", memInfo[0].Name);
    }
}


Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.