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?

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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);
    }
}

1 Comment

That's great. Adrian of course is also right but it's always nice to see an example to help think of a solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.