Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the description attributes At class level

Tags:

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?

like image 214
Graviton Avatar asked May 19 '10 08:05

Graviton


People also ask

How do you find the attributes of a class?

Your class object needs to define __init__(self) and x needs to be self. x=1. Then assign t = T() and use print(vars(t)) and it will show you a dictionary of all the class attributes.

What are the attributes of a class?

Class attributes are the variables defined directly in the class that are shared by all objects of the class. Instance attributes are attributes or properties attached to an instance of a class. Instance attributes are defined in the constructor. Defined directly inside a class.

How could you retrieve information about a class C#?

First, declare an instance of the attribute you want to retrieve. Then, use the Attribute. GetCustomAttribute method to initialize the new attribute to the value of the attribute you want to retrieve. Once the new attribute is initialized, you simply use its properties to get the values.

How do you set a class attribute in Python?

Use dot notation or setattr() function to set the value of class attribute. Python is a dynamic language. Therefore, you can assign a class variable to a class at runtime. Python stores class variables in the __dict__ attribute.


2 Answers

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.

like image 160
Jon Skeet Avatar answered Sep 30 '22 03:09

Jon Skeet


Use reflection and Attribute.GetCustomAttributes

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

like image 35
Raj Kaimal Avatar answered Sep 30 '22 04:09

Raj Kaimal