Laurian

Laurian

  • NA
  • 3
  • 0

Get the name of a specific attribute / property...

Jan 2 2008 4:48 AM
Hi all
I would like to get the name of an attribute, a property, a value at design time. Two examples:
1) The name of a Color

private const string GAINSBORO_COLOR_NAME = "Gainsboro";
[DefaultValue(typeof(Color), GAINSBORO_COLOR_NAME)]
public Color MyColor
{
    get {return _color;}
    set {_color = value;}
}

Here instead of hard-coding "Gainsboro", I would like to do something like GetName(Color.Gainsboro).

2) The name of an attribute

public class Example
{
    public const string FOO_NAME = "foo";
    private string foo;

    public static Dictionary<string, string> SerializeObject(object my_object)
    {
        Dictionary<string, string> serialization = new Dictionary<string, string>();
        foreach (PropertyInfo property in my_object.GetType().GetProperties())
        {
            serialization.Add(property.Name, value.ToString());
        }
        return serialization;
    }

    public static void DoStuffs(Example e)
    {
        Dictionary<string, string> serialization = SerializeObject(e);
        string foo_value = serialization.Values[FOO_NAME];
    }
}

Same as example 1: instead of hard-coding "foo" I would like to get it dynamically (so that if I change foo to bar I don't have to change "foo" to "bar").

I guess these things can be done with Reflexion but I have no idea how... I    welcome any help!
One last thing: I'de rather do it with .NET 2.0 but if the solution does not exists with 2.0 or is neater with a more recent version of the framework, it'll do with 3.0/3.5