views:

749

answers:

2

I use an anonymous object to pass my Html Attributes to some helper methods. If the consumer didn't add an ID attribute, I want to add it in my helper method.

How can I add an attribute to this anonymous object?

+5  A: 

I assume you mean anonymous types here, e.g. new { Name1=value1, Name2=value2} etc. If so, you're out of luck - anonymous types are normal types in that they're fixed, compiled code. They just happen to be autogenerated.

What you could do is write new { old.Name1, old.Name2, ID=myId } but I don't know if that's really what you want. Some more details on the situation (including code samples) would be ideal.

Alternatively, you could create a container object which always had an ID and whatever other object contained the rest of the properties.

Jon Skeet
A: 
public static string TextBox(this HtmlHelper html, string value, string labelText, string textBoxId, object textBoxHtmlAttributes, object labelHtmlAttributes){}

This would accept the id value the textbox should have and the label should refer to. If the consumer now doesn't include the "id" property in the textBoxHtmlAttributes, the method will create an incorrect label.

I can check through reflection if this attribute is added in the labelHtmlAttributes object. If so, I want to add it or create a new anonymous object that has it added. But because I can't create a new anonymous type by walking through the old attributes and adding my own "id" attribute, I'm kind of stuck.

A container with a strongly typed ID property and then an anonymous typed "attributes" property would require code rewrites that don't weigh up to the "add an id field" requirement.

Hope this response is understandable. It's the end of the day, can't get my brains in line anymore..

borisCallens
Well... you *could* create a new type (with CodeDOM etc) which contained the relevant properties. But the code would be ugly as hell. Can I suggest that instead of taking an object and looking at the properties via reflection, you take a IDictionary<string,string> or something? (Continued)
Jon Skeet
You could build that dictionary up with a helper method which did the whole reflection thing - and possibly have a wrapper method which did precisely that - but a dictionary sounds like it's closer to what you're really trying to represent; anonymous object initializers are just syntactically handy.
Jon Skeet