5

I am attempting to use reflection to determine which Properties of a Type have a certain Attribute. This seems to work fine when I create a custom attribute myself, but is currently not working for an attribute in a 3rd party assembly.

The assembly in question is SolrNet, and the Attribute is of Type SolrField.

Example class with usage:

public class PublicDocument : SearchItem {

    [SolrField("case")]
    public string CaseNumber { get; set; }

    [SolrField("case_name")]
    public string CaseName { get; set; }
}

Here is my code for getting at these Attributes. The curious thing is that the property.Attributes is empty! EDIT: After looking again, this property will be empty even with other custom types and seems to be reserved for framework Attributes.

        PublicDocument item = new PublicDocument();
        foreach (PropertyInfo property in item.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) {

            foreach (object attribute in property.GetCustomAttributes(typeof(SolrField), true)) {
                //do some stuff here
            }
        }

SolrField is defined here: https://github.com/mausch/SolrNet/blob/master/SolrNet/Attributes/SolrFieldAttribute.cs

As I said, this same code works fine with an attribute defined in one of my own assemblies and used in the same pattern. So my question here is, can Attributes be marked to not show up through reflection like this, or is there another issue here?

Brendan Hannemann
  • 2,084
  • 1
  • 18
  • 33
  • 1
    possible duplicate of [Is there a framework attribute to hide a member from reflection in .Net?](http://stackoverflow.com/questions/606095/is-there-a-framework-attribute-to-hide-a-member-from-reflection-in-net) – Roman Aug 25 '11 at 21:13
  • 2
    According to the question above, no you can't hide from reflection, so the issue is most likely elsewhere. – Roman Aug 25 '11 at 21:14

1 Answers1

6

Hard to tell for sure. My first guess would be that you might use typeof(SolrFieldAttribute) instead of typeof(SolrField).

sblom
  • 26,911
  • 4
  • 71
  • 95
  • Thanks, this does seem to give me an Attribute back in my inner foreach, and I can therefore move forward with my program. I am still baffled by how this translation works though. How does `SolrField` map to `SolrFieldAttribute`? I may need to get input from the primary maintainer. – Brendan Hannemann Aug 25 '11 at 21:20
  • 3
    That's part of the C# language -- a convention for attributes. When you add an attribute `[SolrField]`, the compiler first looks for a class called `SolrFieldAttribute` and uses that if found, otherwise it looks for a class called `SolrField`. – Joe White Aug 25 '11 at 21:22
  • I would have thought that this was the error, it would just not compile? – Johnny5 Aug 25 '11 at 21:22
  • It compiles fine actually, Joe helped with the mystery. – Brendan Hannemann Aug 25 '11 at 21:27