Can I use Attributes with Anonymous classes?

Solution 1:

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

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

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

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

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

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

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

[1] The one exception to this is ENC operation

Solution 2:

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

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

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