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?
Anonymous types typically are used in the select clause of a query expression to return a subset of the properties from each object in the source sequence. For more information about queries, see LINQ in C#. Anonymous types contain one or more public read-only properties.
The compiler gives them a name although your application cannot access it. From the perspective of the common language runtime, an anonymous type is no different from any other reference type, except that it cannot be cast to any type except for object.
The following extension class would get you what you need.
public static class ObjectExtensions { public static IDictionary<string, object> AddProperty(this object obj, string name, object value) { var dictionary = obj.ToDictionary(); dictionary.Add(name, value); return dictionary; } // helper public static IDictionary<string, object> ToDictionary(this object obj) { IDictionary<string, object> result = new Dictionary<string, object>(); PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(obj); foreach (PropertyDescriptor property in properties){ result.Add(property.Name, property.GetValue(obj)); } return result; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With