Adding attribute on object during run time not happening

attributes, c#, object, typedescriptor

Solution

Unfortunately this method does not dynamically change the metadata of the type, ultimately it only gives you back a TypeDescriptor which includes the attributes you added.

You need to keep the return value of the AddAttributes method and query from there instead...

var myObject = { ... }

var typeDescriptionProvider = TypeDescriptor.AddAttributes(myObject, attrList.ToArray());

var attributes = typeDescriptionProvider.GetTypeDescriptor(myObject).GetAttributes();

You can think of the type descriptor as a union of the type metadata itself (fixed), and any meta data you added at runtime (dynamic).

Problem

I try to add attributes on a certain object. This object can be int, string, List or whatever. I try to use `TypeDescriptor.AddAttributes(object, attrList.ToArray());` but this list of attributes do not show up when I do: `object.GetType().GetCustomAttributes(false)` How come? Best regards, Gabriel Paulsson

Original source