tags:

views:

38

answers:

1

Given an instance of a class I want to set properties on attributes at runtime.

So I tried this, but as far as I can tell this finds the attributes on the class not the instance, so any changes I make to the attribute properties have no effect.

var properties = myObject.GetType().GetProperties();

foreach (object prop in properties)
{
   var attribute =prop.GetCustomAttributes(typeof(MyAttribute), true)[0];
   //attribute.MyProp do some stuff
}

If I try using type descriptor like below, there is no way of getting to the attributes on the properties.

var myObject= (MyClass) object;
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(myObject);

//There is no props[0].GetCustomAttributes(
+2  A: 

Attributes are metadata you apply to a Type, or a Member of a Type, not an instance. If you are applying values to a specific instance of a class, shouldn't you consider using properties/fields?

Matthew Abbott
Well I am trying to get around the fact that attributes only take compile time constants as params, so I need to dynamically supply some values.
Dan
Well, you can get an instance of the attribute if you needed to, as long as you have a use for that attribute. The question you would ask, is if you are going to all the effort to get an instance of an attribute to apply runtime values to it, what use is it of being an attribute?
Matthew Abbott