Home > Backend Development > C++ > How to Dynamically Add C# Properties at Runtime Without Using Collections?

How to Dynamically Add C# Properties at Runtime Without Using Collections?

Barbara Streisand
Release: 2025-01-02 21:12:40
Original
398 people have browsed it

How to Dynamically Add C# Properties at Runtime Without Using Collections?

Dynamically Add C# Properties at Runtime Without Using Collections

Consider a scenario where you need to create a dynamic object with properties that can be added dynamically at runtime. Instead of using a dictionary or collection of parameters, you can leverage the ExpandoObject class.

ExpandoObject

ExpandoObject allows you to add and remove members of its instances at runtime, enabling dynamic binding capabilities. It provides a convenient way to manipulate properties dynamically, as seen in the following example:

dynamic dynObject = new ExpandoObject();
dynObject.SomeDynamicProperty = "Hello!";
Copy after login

Custom Dynamic Object

Building on the ExpandoObject approach, you can create a custom dynamic object that manages the retrieval and setting of dynamic properties. The following code demonstrates this concept:

public static dynamic GetDynamicObject(Dictionary<string, object> properties)
{
    return new MyDynObject(properties);
}

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

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

    public override IEnumerable<string> GetDynamicMemberNames()
    {
        return _properties.Keys;
    }

    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;
        }
    }

    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

By implementing the DynamicObject interface, you gain full control over the dynamic member access mechanism. This allows you to implement custom rules and behaviors for your dynamic object.

Usage

With your custom dynamic object in place, you can add properties and retrieve them at runtime:

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

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

Note:

Dynamic objects are powerful but must be used with caution. The compiler cannot verify dynamic calls, and you may encounter runtime errors if you're not careful. It's crucial to understand the underlying mechanics and potential issues before using them in production code.

The above is the detailed content of How to Dynamically Add C# Properties at Runtime Without Using Collections?. 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