Access Attribute information via reflection - CSharp Custom Type

CSharp examples for Custom Type:Attribute

Description

Access Attribute information via reflection

Demo Code

using System;/*from  w  w w.jav a 2 s  .  co m*/
[AttributeUsage(AttributeTargets.All)]
public class HelpAttribute : System.Attribute
{
    public readonly string Url;
    public string Topic   // Topic is a named parameter 
    {
        get
        {
            return topic;
        }
        set
        {
            topic = value;
        }
    }
    public HelpAttribute(string url)   // url is a positional parameter 
    {
        this.Url = url;
    }
    private string topic;
}

[HelpAttribute("Information on the class MyClass")]
class MyClass
{
}

class Program
{
    static void Main(string[] args)
    {
        System.Reflection.MemberInfo info = typeof(MyClass);
        object[] attributes = info.GetCustomAttributes(true);
        for (int i = 0; i < attributes.Length; i++)
        {
            System.Console.WriteLine(attributes[i]);
        }
    }
}

Result


Related Tutorials