0

I need to add an attribute to some property in runtime (for design-time purposes). I know I can do this for classes:

TypeDescriptor.AddAttributes(typeof(MyType), new MyRuntimeAttribute());

But I can't find any way to do the same for properties.

Any suggestions?

UPD: The exactly task is following:

public class BaseClass {
  public BaseClass(string name) { Name = name; }
  public Name { get; set; }
}
public class Descendant1: BaseClass {
  public Descendant1() : base("Default Name 1") { }
}
...
public class DescendantN: BaseClass {
  public DescendantN() : base("Default Name N") { }
}

I want each of the descendants to have each own DefaultValueAttribute at the Name property with the corresponding default name. And I don't want to hardcode DefaultValueAttribute on each descentand :)

Beresta
  • 696
  • 1
  • 7
  • 9

2 Answers2

0

You can't dynamically add or remove attributes. Note that TypeDescriptor doesn't actually add an attribute to the class either: If you check the array that typeof(MyType).GetCustomAttributes(false) returns after you attach your attribute with MyRuntimeAttribute you'll notice that it isn't part of it.

Since you mention design-time, what you can do is dynamically modify attributes. Is that what you actually want to do?

See also:

Community
  • 1
  • 1
Hound
  • 713
  • 5
  • 14
  • Sorry, but no. I've just investigate a little and now I think that TypeConverter implementation with GetProperties override is that what I need (PropertyDescriptorAdaptor will return modified AttributesCollection; based on http://msdn.microsoft.com/en-us/library/system.componentmodel.propertydescriptor.aspx article). I'll post here a results after some tests. However, thank you for the second link, answer posted there is very interesting. – Beresta Jul 12 '10 at 18:51
  • https://stackoverflow.com/questions/14663763/how-to-add-an-attribute-to-a-property-at-runtime – Impostor Apr 05 '18 at 13:02
  • @Dr.Snail: Read that code again: That's not adding an attribute to an existing class, it's deriving the class during runtime and adding an attribute to that one. – Hound Apr 13 '18 at 13:28
0

You can also provide a control designer and in that designer you can override PreFilterProperties. While typically this is used to hide properties, it can also be used to add them.

http://www.codeproject.com/KB/webforms/HidingProperties.aspx

Tergiver
  • 14,171
  • 3
  • 41
  • 68