Question

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

Was it helpful?

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top