As you know in C# we have something called Object and collection initializer. For example we can use object initializer to create name and value pairs for different properties of the object, in this case
As you can see we used object initializer for those embedded objects too. Although object initializers can be used for anonymous types. So here’s the same example which we build with anonymous object:
As you can see we use key/value pairs. Actually it’s a little different from C# for instance we used colons (
:) instead of equals (
=) but generally the syntaxes are similar. In some case you may see the name is embedded in quotes, it’s optional but if you’re using any reserved characters like space, in this case, you need to surround the name with quotes (like
You can also use a bracket syntax, that’s why objects are sometimes called associative arrays:
This way we can retrieve or set the property values. There are other ways for accessing and retrieving property value that are as follows:
We can also get embedded objects that are the properties of those dynamic objects as well and retrive properties from them:
ExpandoObject gives you this behavior.
ExpandoObject Represents an object whose members can be dynamically added and removed at run time.
For example in this code we are creating a new object and marking it as dynamic so that we can add members to this
ExpandoObject as we want:
These are being added on-the-fly. It means that these aren’t defining the shape ahead of time. We are just saying we are going to add properties to the
We can still add another property or function on-the-fly: