1

I am wanting to access the custom attributes on a Field in the class. I want to access the attributes placed on the field during the fields constructor. Is this possible?

Edit 06/28/09 Something like the below pseudo code

class SpecialInt

{

int _intVal; 
int _maxVal; 
public SpecialInt() 
{ 
    //Get attribute for the instantiated specialint 
    _maxVal = GetAttribute("MaxValue") 

} }

class main()

{

[MaxValue(100)] 
SpecialInt sInt; 
public main() 
{ 
    sInt = new SpecialInt() 
} 

}

2 Answers 2

6

Sure this is possible. Attributes are stored in Metadata and this is easily accessible during construction of an object.

public class Foo { 
  [Something]
  public int Field1;

  public Foo() {
    FieldInfo fi = typeof(Foo).GetField("Field1");
    SomethingAttribute si = (SomethingAttribute)fi.GetCustomAttribute(typeof(SomethingAttribute),false)[0];
    // grab any Custom attribute off of Fiield1 here
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

What I sort of want to be able to do. class SpecialInt { int _intVal; int _maxVal; public SpecialInt() { //Get attribute for the instantiated specialint _maxVal = GetAttribute("MaxValue") } } class main() { [MaxValue(100)] SpecialInt sInt; public main() { sInt = new SpecialInt() } } And have the constructor for SpecialInt know the attributes applied to it.
1

You can test them from anywhere. Attributes are inserted into the metadata for the type when you compile it. A type doesn't need to be instantiated to access field properties.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.