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

1

1 Answer 1

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
};
Sign up to request clarification or add additional context in comments.

3 Comments

ExpandoObject, now my favorite object of .NET :)
Do not overuse ExpandoObject. Don't abandon compile-time type-safety unless you really need to.
Actually found a Skeet-Link to this topic: stackoverflow.com/questions/1394117/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.