views:

191

answers:

2

Consider the following custom attribute:

[Abc.Text(MaxLength=33)]
public Abc.Text heading = new Abc.Text();

MaxLength is defined in the class TextAtrribute:

public class TextAttribute : Attribute
{
  public int MaxLength {get; set;}

}

In other code I have, the Text class needs to know its MaxLength.

Is there a way I could do something like this:

int max = (int)heading.GetAttribute("MaxLength");

Comments on Answers

This modification of RexM's answer worked:

System.Reflection.FieldInfo headingField = this.GetType().GetField("heading");
object[] attribs = headingField.GetCustomAttributes(typeof(Abc.TextAttribute), true);

if (attribs.Length == 1)
{
  int max = ((Abc.TextAttribute)attribs[0]).AbcMaxLength;
}

But I was hoping I could do it without the reference to "this", the parent of the field. Can you get a field's parent somehow? That would solve it eg

System.Reflection.FieldInfo headingField = heading.GetParent().GetType().GetField("heading");
+3  A: 

Use the GetCustomAttributes() method on the Type of your current object. That will return an array of objects representing instance(s) of the attributes on that type which are of the attribute type you specify:

object[] attribs = this.GetType().GetCustomAttributes(typeof(Abc.Text));
if (attribs.Length == 1)
{
    int max = ((Abc.Text)attribs[0]).MaxLength;
}

Edit: OK, with your clarifications I understand a bit better what you're trying to do. I think I misread your code sample the first time. It's essentially the same concept, but the attribute is on a field, not the class:

System.Reflection.FieldInfo headingField = this.GetType().GetField("heading");
object[] attribs = headingField.GetCustomAttributes(typeof(Abc.Text));
if (attribs.Length == 1)
{
    int max = ((Abc.Text)attribs[0]).MaxLength;
}

Edit again: In order to get a handle to the field, you have to know the type on which the field lives. An easy way is to use this.GetType() but you can also do something like:

FieldInfo headingField = typeof(MyClass).GetField("heading");
Rex M
See my comment in the question. This doesn't return any attributes
Petras
@Petras I updated my answer accordingly.
Rex M
OK, have updated mine too. Still not quite what I want.
Petras
@Petras see my latest addition
Rex M
A: 

You can read here how to do what you want.

Type type = TextAttribute.GetType();
PropertieInfo pi = type.GetProperty("MaxLength");
if (pi.CanRead())
  //the value
  pi.GetValue();
eKek0
PropertyInfo is for accessing properties on a type, not attributes.
Rex M