none
Custom Attributes RRS feed

  • Question

  • I have used custom attributes for a while, mainly the default [*] and [assembly: *]. But I have seen other target modifiers also such as [return: *] and [param: *]. What are these for and how do I use them? I cant seem to find anything about the purpose of these... Can a attribut be added to a return value? How can I retrieve that attribute?

    Has this anything to do with Aspect Oriented Programming?

    /Andreas
    Tuesday, November 25, 2008 3:22 PM

Answers

  • According to the C# language spec, the attribute target is optional. You could for example, type the following:

    [type:Description("A class that does stuff")]  
    public class Foo  
    {  

    But C# can pick up the fact that the attribute is applied to the class (aka type) from the context of its position in the code. So normally, you don't specify the target.

    However, there are some cases where there is no contextual information for the compiler to know where to attach the attribute. The most common example target is [assembly:*]. Return values are another area where you might see it used:

    [return: MarshalAs(UnmanagedType.SysInt)]  
    public IntPtr Bar([MarshalAs(UnmanagedType.U4)] int x)  
    {  
        return x + 1;  
    }  
     

    Notice that the "x" parameter had an in-line attribute, so it doesn't need the target specified, but the return value did (otherwise it would be ambiguous as to whether the attribute applied to the method or just the return value).

    Another example is when you declare a class with an event. The event declaration causes the compiler to create a hidden delegate field, and the only way to attach an attribute to that field is to use the [field:*] target specification.

    You can get these attribute values via reflection just like attributes that don't use the target specifiers. They all look the same to IL.

    And along the same lines, they have as much (or as little) to do with AOP as attributes without target specifiers.
    -Rob Teixeira
    • Proposed as answer by Loukoum Friday, November 28, 2008 7:43 AM
    • Marked as answer by Zhi-Xin Ye Monday, December 1, 2008 8:10 AM
    Tuesday, November 25, 2008 7:30 PM