Question

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
};
Was it helpful?

Solution

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

OTHER TIPS

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.

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

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

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