7

If I have a class like this

[Attr("Blah",
 Data = "Blah")]
public class Test : SuperClass{}

Is there a way I can change the values of the attribute of an instance of the class at runtime? eg in pseudo code

SuperClass test = new Test();
test.Attr.Value = "blah1";
test.Attr.Data = "blah2";

(I have an instance of the class I want to change the attributes on, cast as a class it extends)

UberMouse
  • 917
  • 2
  • 12
  • 26
  • possible duplicate of [Change Attribute's parameter at runtime](http://stackoverflow.com/questions/51269/change-attributes-parameter-at-runtime) – Alastair Pitts Mar 13 '13 at 00:39
  • I've already looked at that, those are method attributes, class attributes seem to be different. At the least that question didn't help me. – UberMouse Mar 13 '13 at 00:51
  • I'm pretty sure you can change these at runtime as they are embedded into the metadata of the assembly. – sa_ddam213 Mar 13 '13 at 01:03
  • I don't want to change them for the class, I only want to change them for the specific instance of the class, you can do this for attributes on Properties afaik, so I was hoping it can be done with class attributes. – UberMouse Mar 13 '13 at 01:04
  • @UberMouse: The top rated answer in the question i linked is an example the uses class attributes. – Alastair Pitts Mar 13 '13 at 02:21
  • It doesn't update the attribute data on a class instance though, it only retrieves it. I'm not entirely sure this is possible. – UberMouse Mar 13 '13 at 02:21

2 Answers2

3

There is no implicit connection between attributes and objects instances. Only between the class and the attribute. The best bet would be to look for the attribute in the constructor and "cache" the values in properties on the object. Of course that doesn't make sense if you are only looking at the Test class, but it does make sense if the constructor of the SuperClass looks for the custom attributes on the type retrieved with "this.GetType()".

Roman Gruber
  • 1,411
  • 11
  • 16
-1

You can change Attribute values at runtime at Class level (not object instance level):

var attr = TypeDescriptor.GetProperties(typeof(UserContact))["UserName"].Attributes[typeof(ReadOnlyAttribute)] as ReadOnlyAttribute;
attr.GetType().GetField("isReadOnly", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(attr, username_readonly);
mmm
  • 61
  • 1
  • 9
  • This is setting the attribute of a property if the class ("UserName"), not on the class ("UserContact"). The question is to set value of a class attribute. – d.popov Sep 30 '15 at 11:54