16

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? :)

Greg
  • 23,155
  • 11
  • 57
  • 79
Alexander Beletsky
  • 19,453
  • 9
  • 63
  • 86
  • possible duplicate of [How do I create dynamic properties in C#?](http://stackoverflow.com/questions/947241/how-do-i-create-dynamic-properties-in-c) – nawfal Jul 20 '14 at 06:23

1 Answers1

35

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
};
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964