15

I can use TypeDescriptor.AddAttributes to add an attribute to a type in runtime. How do I do the same for a method and parameter? (maybe 2 separate questions...)

MatteS
  • 1,542
  • 1
  • 16
  • 35

2 Answers2

18

TypeDescriptor.AddAttributes only affects a very specific use-case; i.e. from within System.ComponentModel. For the rest of reflection, it knows nothing about the extra attribute. And indeed, System.ComponentModel doesn't really apply to methods or parameters.

So in short; you can't. You will need to store this information somewhere else (bespoke), or add it at compile-time.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • @Mark Gravell, Any workaround to add property-metadata in a Silverlight project (where `TypeDescriptor` and `TypeDescriptionProvider` aren't implemented? – Shimmy Weitzhandler Feb 25 '12 at 22:00
  • @Shimmy not as far as I know, no. – Marc Gravell Feb 25 '12 at 22:40
  • @Shimmy btw - if you're going to flag something as a duplicate, please say "of what" (in fact, there's a vote-type just for that) – Marc Gravell Feb 25 '12 at 22:42
  • @MarcGravell, [this](http://stackoverflow.com/a/2397617/75500) is a duplicate of [your answer](http://stackoverflow.com/a/2397585/75500), which you posted 9 minutes earlier. – Shimmy Weitzhandler Feb 25 '12 at 23:34
  • @MarcGravell, as per my issue, first let me describe what is my actual case. I have a `User` class that implements `IUser` on the server. The generated client-entity implement `IIdentity.IsAuthenticated`, and I wanted to attribute it with `[Display(AutoGenerateField=false)]`. I tried to make a matching dummy property on server and mark it with `Exclude` so it's not generated twice, then add metadata for it in the metadata body class, the metadata should be generated for the existing property on the client as well, but that didn't work. Generated `IsAuthenticated` remains unattributed on client – Shimmy Weitzhandler Feb 26 '12 at 00:47
0

As I see from analyzing the TypeDescriptor class in Reflector, the .AddAttributes method internally calls the .AddProvider method. The TypeDescriptionProvider instance passed to it is actually responsible for providing meta-data. You could try adding the [TypeDescriptionProviderAttribute] attribute to your class and implement your own provider by deriving from the TypeDescriptionProvider class. As the documentation says, by overriding TypeDescriptionProvider.CreateInstance, you could provide a substitute object whose type has all necessary attributes. I suspect that the attributes applied to methods inside the substitution type will also take effect. However, I haven't tried that myself, so feel free to experiment...

Kerido
  • 2,930
  • 2
  • 21
  • 34