Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add property to dynamic object .NET

Tags:

c#

.net

dynamic

I probably want too much, but my scenario is

public dynamic CreateConfigObject(JobConfigurationModel config) {
    dynamic configObject = new { };

    configObject.Git = new GitCheckout {
        Repository = config.Github.Url
    };

    return configObject;
}

Of course, it fails on configObject.Git since this property does not exist. I want to be able to add any number of properties at run time, with out any beforehand knowledge of number and names of properties;

Is such case possible in C# at all, or my ill JavaScript imagination starts to hurt me? :)

like image 962
Alexander Beletsky Avatar asked Jul 14 '11 19:07

Alexander Beletsky


People also ask

How do I add property to expandoObject?

We will add the Language property. // Add properties dynamically to expando AddProperty(expando, "Language", "English"); The AddProperty method takes advantage of the support that ExpandoObject has for IDictionary<string, object> and allows us to add properties using values we determine at runtime.

How do you handle a dynamic object in C#?

You can use a dynamic object to refer to a dynamic script that is interpreted at run time. You reference a dynamic object by using late binding. In C#, you specify the type of a late-bound object as dynamic . In Visual Basic, you specify the type of a late-bound object as Object .

What is dynamic property in C#?

In C# 4.0, a new type is introduced that is known as a dynamic type. It is used to avoid the compile-time type checking. The compiler does not check the type of the dynamic type variable at compile time, instead of this, the compiler gets the type at the run time.


1 Answers

dynamic allows loosely-typed access to strongly-typed objects.

You should use the ExpandoObject class, which allows loosely-typed access to an internal dictionary:

dynamic configObject = new ExpandoObject();

configObject.Git = new GitCheckout {
    Repository = config.Github.Url
};
like image 173
SLaks Avatar answered Oct 06 '22 08:10

SLaks