How to create and use custom attributes

To create a custom attribute for classes , methods or properties you have to create a new class inheriting from System.Attribute This is a sample for a custom attribute class

[AttributeUsageAttribute(AttributeTargets.All,AllowMultiple=true)]
public class Author:System.Attribute
{
     public Author(string name)
     {
           this.Name = name;
     }
     public string Name
     {
           get; set;
     }
}

and you can then use it like this

public class ClassWithCustomAttribute
{
     [Author("Mustafa Refai")]
     //here is the custom attribute
     public string Property1
     { 
           get; set;
     }
}

Ebook Download
View all
Learn
View all