Page 143 - CSharp/C#
P. 143

Chapter 16: Attributes




        Examples



        Creating a custom attribute


         //1) All attributes should be inherited from System.Attribute
         //2) You can customize your attribute usage (e.g. place restrictions) by using
         System.AttributeUsage Attribute
         //3) You can use this attribute only via reflection in the way it is supposed to be used
         //4) MethodMetadataAttribute is just a name. You can use it without "Attribute" postfix - e.g.
         [MethodMetadata("This text could be retrieved via reflection")].
         //5) You can overload an attribute constructors
         [System.AttributeUsage(System.AttributeTargets.Method | System.AttributeTargets.Class)]
         public class MethodMetadataAttribute : System.Attribute
         {
             //this is custom field given just for an example
             //you can create attribute without any fields
             //even an empty attribute can be used - as marker
             public string Text { get; set; }

             //this constructor could be used as [MethodMetadata]
             public MethodMetadataAttribute ()
             {
             }

             //This constructor could be used as [MethodMetadata("String")]
             public MethodMetadataAttribute (string text)
             {
                 Text = text;
             }
         }


        Using an attribute



         [StackDemo(Text = "Hello, World!")]
         public class MyClass
         {
             [StackDemo("Hello, World!")]
             static void MyMethod()
             {
             }
         }



        Reading an attribute


        Method GetCustomAttributes returns an array of custom attributes applied to the member. After
        retrieving this array you can search for one or more specific attributes.


         var attribute = typeof(MyClass).GetCustomAttributes().OfType<MyCustomAttribute>().Single();


        Or iterate through them


        https://riptutorial.com/                                                                               89
   138   139   140   141   142   143   144   145   146   147   148