Can I use Attributes with Anonymous classes?

will picture will · Aug 1, 2009 · Viewed 8.9k times · Source

I have a anonymous class:

var someAnonymousClass = new
{
    SomeInt = 25,
    SomeString = "Hello anonymous Classes!",
    SomeDate = DateTime.Now
};

Is there anyway to attach Attributes to this class? Reflection, other? I was really hoping for something like this:

var someAnonymousClass = new
{
    [MyAttribute()]
    SomeInt = 25,
    SomeString = "Hello anonymous Classes!",
    SomeDate = DateTime.Now
};

Answer

JaredPar picture JaredPar · Aug 1, 2009

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