views:

96

answers:

2

Suppose I have a class named Data. Another class annotates one of its members, of type data, with some attribute. For example:

public class Example{

    [DefaultNameAttribute("default name")]
    public Data Name{get;set}
}

What I'm looking for is a way, from within the class Data, to retrieve that attribute and the data it contains. I want to be able to write the following code:

public class Data{
    private string _name = null;
    public string Name{
        get{
            if (_name != null) return _name;
            return (getDefaultNameFromAnnotation(this));//this is the method I'm looking for
        }
}

In other words, I want to be able to give a default value to a specific field using custom attributes specified outside my class.

A: 

It will depend on how your attribute is used (if it is on a class, property, method, etc...). For example if it is only used on a class you could get all types that are marked with your attribute with the following code:

public IEnumerable<Type> GetTypes(Assembly assembly) 
{
    foreach(Type type in assembly.GetTypes()) 
    {
        if (type.GetCustomAttributes(typeof(DefaultNameAttribute), true).Length > 0) 
        {
            yield return type;
        }
    }
}

If it is only used on properties (as your example), then you could nest an additional foreach statement that will enumerate all properties for a given type and look for the attribute.

Darin Dimitrov
A: 

Short answer : You can't, or at least, you should not.

The DefaultNameAttribute is applied on a member of Example type, which is decorrelated from Data type. There could be several types that use Data type, and several instances of the DefaultNameAttribute. Example can even be defined in another assembly, etc.

Romain Verdier