Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DefaultMemberAttribute - what does it do?

I've already read the MSDN article about it. It seems internally it is the way c# sets which is the function that is going to work as indexer(am I right?). Now, I've seen the following example:

[DefaultMemberAttribute("Main")]
public class Program {

    public static void Main() {
        ...
    }
}

Now, I don't get it what it means.


Thanks all. But I still can't get its usefulness, apart from the indexer thing. When are we going to call InvokeMember?

like image 220
devoured elysium Avatar asked Jul 13 '09 14:07

devoured elysium


2 Answers

No, the DefaultMemberAttribute is used by languages such as VB.NET to find out the member that is acted on by default if no member is referenced from an object, i.e. the member invoked by InvokeMember. This is often used in conjunction with indexers, as you noted, but it is not used by C# directly (unless you use InvokeMember explicitly).

However, for the benefit of other .NET languages, C# does emit the DefaultMemberAttribute for the indexer of a class (if it has one), as indicated by MSDN:

The C# compiler emits the DefaultMemberAttribute on any type containing an indexer. In C# it is an error to manually attribute a type with the DefaultMemberAttribute if the type also declares an indexer.

I think MSDN confuses things by referring to indexers a lot in the remarks but then giving an example that does not use an indexer. To clarify, the default member can be anything, but C# gives special behavior for indexers by emitting the attribute for you (if an indexer exists) to the exception of all other use cases.

like image 131
Jeff Yates Avatar answered Oct 17 '22 00:10

Jeff Yates


I personally have never used it, but as far as I can tell you are defining the default method to be invoked when calling InvokeMember. So, using the code snippet you provided if I was to say:

Program prog = new Program();
typeof(Program).InvokeMember("", null, null, prog, null);

Because I left the first argument empty of the InvokeMember call it would use the attribute to determine what the default member is of your class, in your case it is Main.

like image 38
joshlrogers Avatar answered Oct 17 '22 01:10

joshlrogers