chobo2
chobo2

Reputation: 85855

How to Get Custom Attribute Back?

Say I have this property with this attribute

[StringLength(3)]
public string Owner { get; set; }

How can i use reflection to get me back

"[StringLength(3)]"

I don't care if it is returned as a string or if I have to rebuild it but I want to have that result that I can access.

Upvotes: 0

Views: 44

Answers (1)

DavidG
DavidG

Reputation: 119146

This should be enough code to get you going, assuming your class is called Test and the property is called Owner:

var attributeStrings = typeof(Test)
    .GetProperty("Owner")
    .CustomAttributes   
    .Select(a => 
        string.Format(
            "[{0}({1})]",
            a.AttributeType.Name.Replace("Attribute",""),
            string.Join(", ", a.ConstructorArguments.Select(ca => ca.Value))
));

Upvotes: 4

Related Questions