user129647
user129647

Reputation:

Using Custom Attributes from Within Constructor - C#

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() 
} 

}

Upvotes: 1

Views: 345

Answers (2)

vgru
vgru

Reputation: 51312

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.

Upvotes: 1

JaredPar
JaredPar

Reputation: 755587

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
  }
}

Upvotes: 6

Related Questions