add a property to an object during runtime in csharp

You can add a property to an object during runtime using reflection in c#. Here's an example:

main.cs
public static void AddProperty(dynamic obj, string propertyName, Type propertyType)
{
    // Create a new dynamic property with the given property name and type
    var dynamicProperty = new DynamicProperty(propertyName, propertyType);

    // Get the object's properties dictionary using reflection
    var properties = (IDictionary<string, object>)obj;

    // Add the dynamic property to the object's properties dictionary
    properties.Add(propertyName, dynamicProperty);
}

// Example usage
dynamic person = new ExpandoObject();
AddProperty(person, "Name", typeof(string));
person.Name = "John";

Console.WriteLine(person.Name); // Output: John
651 chars
19 lines

In this example, we use the ExpandoObject class to create a dynamic object with no predefined properties. The AddProperty method takes the dynamic object, the name of the property to add, and the type of the property as input parameters.

The method creates a new DynamicProperty object with the given property name and type. The DynamicProperty class is a simple class that stores the name and type of a dynamic property.

Next, the method uses reflection to get the object's properties dictionary and adds the dynamic property to it. Finally, we can set the value of the property as usual with the syntax object.property = value.

Note that this approach is not efficient and should be used with caution, especially in performance-critical scenarios.

gistlibby LogSnag