Why doesn't TypeDescriptor.GetAttributes(person)
return the attribute when Person
is a struct?
TypeDescriptor.AddAttributes
and TypeDescriptor.GetAttributes
use reference equality to find objects in TypeDescriptor
's internal cache. If Person
is a class, then the person
arguments in those two method calls reference the same instance. However, if Person
is a struct, then the person
arguments get boxed independently into different instances, so GetAttributes
is unable to find the original person
.
If person
is only boxed once, then the code works as expected:
object person = new Person(); // `object` instead of `var`
Why does typeDescriptionProvider.GetTypeDescriptor(person).GetAttributes()
always return the attribute?
The TypeDescriptionProvider.GetTypeDescriptor(Object)
documentation isn't clear (at least to me), but note that you can apparently pass anything to typeDescriptionProvider.GetTypeDescriptor
— like 42
(a struct) or "Hello, World!"
(a class) — and get your attribute back:
var descriptionAttributesUsingTdp = typeDescriptionProvider.GetTypeDescriptor(42)
.GetAttributes().OfType<DescriptionAttribute>().ToList();
// descriptionAttributesUsingTdp.Count == 1
Based on this behavior, my guess is that the typeDescriptionProvider
returned by TypeDescriptor.AddAttributes(person, ...)
is not associated with the person
. Instead, it represents a plug-in that can add your attribute to any object, and GetTypeDescriptor
is the method that does so.