0

I would expect there to be three lines of output from this code, but there are none:

[AttributeUsage( AttributeTargets.Property )]
public class FieldAttribute : System.Attribute
{
  public String FieldName
  {
    get;
    set;
  }
}

public class Host
{

  [Field]
  public String FieldOne
  {
    get;
    set;
  }

  [Field(FieldName="Foo")]
  public String FieldTwo
  {
    get;
    set;
  }

  [FieldAttribute]
  public String FieldThree
  {
    get;
    set;
  }

  public String FieldFour
  {
    get;
    set;
  }
}


class Program
{
  static void Main( string[] args )
  {
    Type t = typeof(Host);
    foreach ( Object att in t.GetCustomAttributes( typeof(FieldAttribute), true ) )
    {
      Console.WriteLine( att.ToString() );
    }
  }
}

Am I missing soemthing obvious?

Andrew

amaca
  • 1,470
  • 13
  • 18
  • Check out this question: http://stackoverflow.com/questions/2281972/c-reflection-how-to-get-a-list-of-properties-with-a-given-attribute – wsanville Mar 06 '11 at 17:28

2 Answers2

3

t.GetCustomAttributes returns the attributes declared on the class itself.

You need to loop through t.GetProperties() and call GetCustomAttributes on the individual PropertyInfos.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Can property attribute be applied to a method? Should not `GetProperties` overload be used instead? –  Mar 06 '11 at 17:31
2

Try something like this in the Main method:

Type t = typeof(Host);
foreach(var prop in t.GetProperties())
{
    var attrs = prop.GetCustomAttributes(typeof(FieldAttribute), true);
    foreach(var attr in attrs)
        Console.WriteLine("{0} - {1}", prop.Name, attr.ToString());
}
rsbarro
  • 27,021
  • 9
  • 71
  • 75