1

I have an existing C# class that I cannot modify, but only use it. By example:

public class Test {}

I would like to add dynamically an attribute (MyAttribute) to this class Test, like:

[MyAttribute(TestMode)]
public class Test {}

Is it possible in C# and how?

Note: of course, I can derive from this Test class and add declaratively the attribute, but it means to create a new class, and I'd like to avoid it.

Alain
  • 422
  • 1
  • 4
  • 9
  • 1
    What do you mean when you say **dynamically**? Do you want to add the attribute at runtime? – Daniel Hilgarth Dec 01 '11 at 10:24
  • Check this thread: http://stackoverflow.com/questions/129285/can-attributes-be-added-dynamically-in-c – esskar Dec 01 '11 at 10:27
  • I second Daniel here. Please clarify what you are trying to accomplish. – jeroenh Dec 01 '11 at 10:27
  • @Daniel: Yes, I want to add the attribute at runtime – Alain Dec 01 '11 at 10:38
  • Maybe you misunderstood what attributes are. Attributes are information about a `Class` and therefore it's absolutely not related with dynamically add information to an `Object`. What do you want do do? I'm sure the solution is something else. – JiBéDoublevé Dec 01 '11 at 10:40
  • A third party system uses a specific attribute to recognize in an assembly some classes its needs. By adding this attribute to the Test class, this one will be recognized too. – Alain Dec 01 '11 at 10:45

1 Answers1

6

Attributes are compiled into metadata and cannot be added at runtime.

http://msdn.microsoft.com/en-en/library/z0w1kczw(v=vs.80).aspx

Felix K.
  • 6,201
  • 2
  • 38
  • 71