How to dynamic new Anonymous Class?
You can create an ExpandoObject like this:
IDictionary<string,object> expando = new ExpandoObject();
expando["Name"] = value;
And after casting it to dynamic, those values will look like properties:
dynamic d = expando;
Console.WriteLine(d.Name);
However, they are not actual properties and cannot be accessed using Reflection. So the following statement will return a null:
d.GetType().GetProperty("Name")
Anonymous types are just regular types that are implicitly declared. They have little to do with dynamic
.
Now, if you were to use an ExpandoObject and reference it through a dynamic
variable, you could add or remove fields on the fly.
edit
Sure you can: just cast it to IDictionary<string, object>
. Then you can use the indexer.
You use the same casting technique to iterate over the fields:
dynamic employee = new ExpandoObject();
employee.Name = "John Smith";
employee.Age = 33;
foreach (var property in (IDictionary<string, object>)employee)
{
Console.WriteLine(property.Key + ": " + property.Value);
}
// This code example produces the following output:
// Name: John Smith
// Age: 33
The above code and more can be found by clicking on that link.