[ACCEPTED]-Can I use Attributes with Anonymous classes?-anonymous-types

Accepted answer
Score: 54

You're actually creating what is called 23 an anonymous type here, not a dynamic one.

Unfortunately 22 no there is no way to achieve what you are 21 trying to do. Anonymous types are meant 20 to be a very simple immutable type consisting 19 of name / value pairs.

The C# version of 18 anonymous type only allows you to customize 17 the set of name / value pairs on the underlying 16 type. Nothing else. VB.Net allows slightly 15 more customization in that the pairs can 14 be mutable or immutable. Neither allow 13 you to augment the type with attributes 12 though.

If you want to add attributes you'll 11 need to create a full type.

EDIT OP asked if 10 the attributes could be added via reflection.

No 9 this cannot be done. Reflection is a way 8 of inspecting metadata not mutating it. Hence 7 it cannot be used to add attributes.

Additionally, type 6 definitions in an assembly, and in general, are 5 immutable and cannot be mutated at runtime 4 [1]. This includes the adding of attributes 3 to a method. So other reflection like 2 technologies cannot be used here either.

[1] The 1 one exception to this is ENC operation

Score: 8

First of all, this is an anonymous type. The 7 word "dynamic" might lead people to think 6 you're talking about a C# 4.0 class implementing 5 dynamic semantics, which you aren't.

Secondly, no, you're 4 not able to do what you ask.

If you need 3 to specify attributes for your properties, you're 2 back to a named type, ie. a normal class 1 or struct.

Score: 7

It is possible to add attributes to an anonymous 6 instance using TypeDescriptor.AddAttributes. You can then later access 5 the attributes using TypeDescriptor.GetAttributes.

This will not add 4 them to the Type instance for the object. So 3 it may not be useful in your case if you 2 do not control the code that retrieves and 1 applies the attributes.

More Related questions