Can I use Attributes with Anonymous classes?
Asked Answered
S

3

49

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
};
Sandstrom answered 1/8, 2009 at 20:36 Comment(1)
Use Dictionary<string, object> to build up the json now you have full control over the property names inline. new Dictionary<string, object> { { "@key", "value" } }Latinalatinate
W
56

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

Waive answered 1/8, 2009 at 20:49 Comment(1)
Wow, C# sucks..Bonheur
S
8

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.

Shovelboard answered 1/8, 2009 at 20:44 Comment(1)
You're right, I meant Anon type, thanks for the clarification.Sandstrom
S
8

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.

Slacks answered 16/10, 2012 at 14:59 Comment(1)
Note, this adds class level attributes, NOT property level attributes mentioned in the example in the question.Diverticulosis

© 2022 - 2024 — McMap. All rights reserved.