Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add property to anonymous type after creation

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?

like image 270
Boris Callens Avatar asked Oct 24 '08 14:10

Boris Callens


People also ask

When can an anonymous type be created?

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.

What is the difference between an anonymous type and a regular data type?

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.


1 Answers

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;     } } 
like image 143
Khaja Minhajuddin Avatar answered Oct 17 '22 14:10

Khaja Minhajuddin