C# – using Attributes

person Jason Huangfolder_openC#, Code, HOW-TOlocal_offer, , access_time May 13, 2015

Attributes in C# is used to embed custom metadata about the code / class in the code.


Microsoft has a very good example on how to write your own custom attribute class:Microsoft Custom Attribute Example.


Here is an example of Custom attribute call Developer. You can use this attribute by using DeveloperAttribute or simply use “Developer”.

[AttributeUsage(AttributeTargets.All)]
public class DeveloperAttribute : Attribute
{
    // Private fields. 
    private string name;
    private string level;
    private bool reviewed;
 
    // This constructor defines two required parameters: name and level. 
 
    public DeveloperAttribute(string name, string level)
    {
        this.name = name;
        this.level = level;
        this.reviewed = false;
    }
 
    // Define Name property. 
    // This is a read-only attribute. 
 
    public virtual string Name
    {
        get {return name;}
    }
 
    // Define Level property. 
    // This is a read-only attribute. 
 
    public virtual string Level
    {
        get {return level;}
    }
 
    // Define Reviewed property. 
    // This is a read/write attribute. 
 
    public virtual bool Reviewed
    {
        get {return reviewed;}
        set {reviewed = value;}
    }
}

Here is an example class that uses the Developer Custom Attribute above:

[Developer("Joan Smith", "1")]
 
// Or use this, with the parameter Reviewed also set
[Developer("Jack Sloan", "1", Reviewed = true)]

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>