Search code examples
c#attributescustom-attributes

What is the "Name=value" in [MyAttribute(Name=value)]


I don't know what phrasing to use to google this.

Consider this attribute:

 [MyAttribute(MyOption=true,OtherOption=false)]

What is the Name=value part? And how can I implement it in my own custom attributes?


Solution

  • You can use this by declaring public instance (non-static) properties or fields:

    [AttributeUsage(AttributeTargets.All)]
    public class MyAttribute : Attribute
    {
        public string TestValue { get; set; }
    }
    
    [My(TestValue = "Hello World!")]
    public class MyClass{}
    

    So it works almost like the object initializer syntax, but with () instead of {}.


    If you provide a constructor with parameters for your attribute, you have to pass the parameters first:

    [AttributeUsage(AttributeTargets.All)]
    public class MyAttribute : Attribute
    {
        public string TestValue { get; set; }
    
        public MyAttribute(int arg)
        {}
    }
    
    [My(42, TestValue = "Hello World!")]
    public class MyClass{}