Home > Backend Development > C++ > How Can I Add C# Properties Dynamically at Runtime?

How Can I Add C# Properties Dynamically at Runtime?

Patricia Arquette
Release: 2024-12-30 20:09:16
Original
927 people have browsed it

How Can I Add C# Properties Dynamically at Runtime?

Dynamically Add C# Properties at Runtime Using ExpandoObject

Adding dynamic properties to objects at runtime is a common requirement in many applications. A common approach to achieve this is to use a dictionary or collection of parameters. However, for scenarios where the number and names of properties are unknown beforehand, this approach falls short.

Using ExpandoObject

The .NET Framework provides a built-in solution for this problem: ExpandoObject. This class allows you to create dynamic objects to which you can add and remove properties at runtime.

// Create a dynamic object
dynamic dynObject = new ExpandoObject();

// Add dynamic properties
dynObject.SomeDynamicProperty = "Hello!";

// Execute dynamic actions
dynObject.SomeDynamicAction = (msg) =>
{
    Console.WriteLine(msg);
};

dynObject.SomeDynamicAction(dynObject.SomeDynamicProperty);
Copy after login

Custom Dynamic Object

For more complicated scenarios, you may want to create your own dynamic object that implements the DynamicObject class. This gives you more control over how dynamic member requests are handled.

public sealed class MyDynObject : DynamicObject
{
    // Member dictionary
    private readonly Dictionary<string, object> _properties;

    public MyDynObject(Dictionary<string, object> properties)
    {
        _properties = properties;
    }

    // Get dynamic member names
    public override IEnumerable<string> GetDynamicMemberNames()
    {
        return _properties.Keys;
    }

    // Try to get a dynamic member
    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        if (_properties.ContainsKey(binder.Name))
        {
            result = _properties[binder.Name];
            return true;
        }
        else
        {
            result = null;
            return false;
        }
    }

    // Try to set a dynamic member
    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        if (_properties.ContainsKey(binder.Name))
        {
            _properties[binder.Name] = value;
            return true;
        }
        else
        {
            return false;
        }
    }
}
Copy after login

Using this approach, you can create dynamic objects with any desired properties:

var dyn = GetDynamicObject(new Dictionary<string, object>()
{
    { "prop1", 12 }
});

Console.WriteLine(dyn.prop1);
dyn.prop1 = 150;
Copy after login

Caution: When using dynamic objects, be aware that the compiler will not be able to verify your dynamic calls, and you may encounter runtime errors or lack of intellisense support.

The above is the detailed content of How Can I Add C# Properties Dynamically at Runtime?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template