Jeff B
Jeff B

Reputation: 8982

Is there a way to put attributes on anonymous type properties?

Is there a way you can put attributes on properties in an anonymous type? Or the anonymous type itself? If not when you create it, perhaps afterwards via reflection?

As a potential use scenario, let me borrow from Dapper:

When providing parameters to execute a query in Dapper, you provide the parameters in an anonymous type:

connection.Query<Foo>(sql, new { Id = guid, Condition = true });

Let's say I needed to communicate something about mapping like maybe we store booleans as text T/F (horrible, but sadly true to real-life experience), so I want to add an attribute to that Condition property to tell Dapper how to map it (again this is a slightly forced example). Is that possible?

Upvotes: 5

Views: 801

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500495

No, you can't do this either at the point of declaration or afterwards with reflection.

The closest you could come would be to use an existing anonymous type as the basis for a new type created with CodeDom, or maybe Mono Cecil.

I suspect you'd be better off just writing the code manually yourself instead.

Upvotes: 6

Related Questions