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? :)
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.
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 .
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.
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
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With