14

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...)

2
  • In what situations do you want the attributes to appear? Commented Mar 7, 2010 at 19:07
  • For reflection, hence I noticed even TypeDescriptor.AddAttribute doesnt work for that. Commented Mar 8, 2010 at 14:38

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

@Mark Gravell, Any workaround to add property-metadata in a Silverlight project (where TypeDescriptor and TypeDescriptionProvider aren't implemented?
@Shimmy not as far as I know, no.
@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)
@MarcGravell, this is a duplicate of your answer, which you posted 9 minutes earlier.
@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
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...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.