Graviton
Graviton

Reputation: 83244

Get the description attributes At class level

I have such a class

[Description("This is a wahala class")]
public class Wahala
{

}

Is there anyway to get the content of the Description attribute for the Wahala class?

Upvotes: 21

Views: 17122

Answers (3)

Oded
Oded

Reputation: 498904

You can use reflection to read attribute data:

System.Reflection.MemberInfo inf = typeof(Wahala);
object[] attributes;
attributes = 
   inf.GetCustomAttributes(
        typeof(DescriptionAttribute), false);

foreach(Object attribute in attributes)
{
    DescriptionAttribute da = (DescriptionAttribute)attribute;
    Console.WriteLine("Description: {0}", da.Description);
}

Adapted from here.

Upvotes: 2

Raj Kaimal
Raj Kaimal

Reputation: 8304

Use reflection and Attribute.GetCustomAttributes

http://msdn.microsoft.com/en-us/library/bfwhbey7.aspx

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1499770

Absolutely - use Type.GetCustomAttributes. Sample code:

using System;
using System.ComponentModel;

[Description("This is a wahala class")]
public class Wahala
{    
}

public class Test
{
    static void Main()
    {
        Console.WriteLine(GetDescription(typeof(Wahala)));
    }

    static string GetDescription(Type type)
    {
        var descriptions = (DescriptionAttribute[])
            type.GetCustomAttributes(typeof(DescriptionAttribute), false);

        if (descriptions.Length == 0)
        {
            return null;
        }
        return descriptions[0].Description;
    }
}

The same kind of code can retrieve descriptions for other members, such as fields, properties etc.

Upvotes: 38

Related Questions