1

I have a DTO that looks like this:

public class MyDto
{
    [MyAttribute("attribute1")]
    public string Property1 {get;set;}

    [MyAttribute("attribute2")]
    public string Property2 {get;set;}
}

If I have the string "attribute1", how do I use that to get to the value of Property1 in an instance of MyDto?

edgarian
  • 871
  • 7
  • 18
  • 1
    This is essentially solved the same way as http://stackoverflow.com/questions/3422407/finding-an-enum-value-by-its-description-attribute – John Alexiou Mar 24 '14 at 18:27

2 Answers2

3

Use Reflection. Unfortunately, there's no way to obtain the property from an attribute: you have to iterate through each property and check its attribute.

Adriano Carneiro
  • 57,693
  • 12
  • 90
  • 123
1

Not the most robust code, but try this:

public class MyAttributeAttribute : Attribute
{
    public MyAttributeAttribute(string value)
    {
        Value=value;
    }
    public string Value { get; private set; }
}

public class MyDto
{
    [MyAttribute("attribute1")]
    public string Property1 { get; set; }

    [MyAttribute("attribute2")]
    public string Property2 { get; set; }
}

class Program
{
    static void Main(string[] args)
    {

        MyDto dto=new MyDto() { Property1="Value1", Property2="Value2" };

        string value=GetValueOf<string>(dto, "attribute1");
        // value = "Value1"
    }

    public static T GetValueOf<T>(MyDto dto, string description)
    {
        if(string.IsNullOrEmpty(description))
        {
            throw new InvalidOperationException();
        }
        var props=typeof(MyDto).GetProperties().ToArray();
        foreach(var prop in props)
        {
            var atts=prop.GetCustomAttributes(false);
            foreach(var att in atts)
            {
                if(att is MyAttributeAttribute)
                {
                    string value=(att as MyAttributeAttribute).Value;
                    if(description.Equals(value))
                    {
                        return (T)prop.GetValue(dto, null);
                    }
                }
            }
        }
        return default(T);
    }
}
John Alexiou
  • 28,472
  • 11
  • 77
  • 133
  • That's great. Adrian of course is also right but it's always nice to see an example to help think of a solution. – edgarian Mar 24 '14 at 21:15