Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Viewing / Retrieving Attributes

Tags:

c#

reflection

Inside a class, I have the following piece of code:

/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Errors", typeof(ErrorsType))]
[System.Xml.Serialization.XmlElementAttribute("Success", typeof(SuccessType))]
[System.Xml.Serialization.XmlElementAttribute("Warnings", typeof(WarningsType))]
public object[] Items {
    get {
        return this.itemsField;
    }
    set {
        this.itemsField = value;
    }
}

Using just reflection, is it possible to retrieve these attributes? I saw 'GetCustomAttributes() on the respective Type, but didnt get much joy.

like image 705
maxp Avatar asked Apr 28 '26 16:04

maxp


1 Answers

You need to retrieve the attributes from the property, not the type itself, like so:

typeof(MyClass).GetProperty("Items").GetCustomAttributes(typeof(XmlElementAttribute), false);

Or more complete (remember to import System.Linq for Cast<> and ToArray() to work):

XmlElementAttribute[] attribs = typeof(TheType)
                  .GetProperty("Items")
                  .GetCustomAttributes(typeof(XmlElementAttribute), false)
                  .Cast<XmlElementAttribute>()
                  .ToArray();
like image 102
Andre Loker Avatar answered May 01 '26 04:05

Andre Loker