Basically I am after C# equivalent of the following JavaScript syntax:
var obj = {id: 1};
obj["prop1"] = 100;
obj["prop2"] = 200;
Is it possible to add properties to C# object dynamically and serialize to JSON using WebAPI controller action?
My C# object:
public class MyObject
{
public int Id { get; set; }
public MyChildObject[] Chidren { get; set; }
public int this[string prop]
{
get { return Chidren.Single(x => x.PropertyName == prop).Value; }
}
}
public class MyChildObject
{
public string PropertyName { get; set; }
public int Value { get; set; }
}
What I'd like to return to the client is this:
{
id: 1,
prop1: 100,
prop2: 200
}
This test passes but obviously only because the properties are accessed at runtime. They are not, however, serialized:
[TestMethod]
public void CanAccessDymaicProperties()
{
var dto = new MyObject
{
Id = 1,
Chidren = new[]
{
new MyChildObject { PropertyName = "prop1", Value = 100 },
new MyChildObject { PropertyName = "prop2", Value = 200 },
}
};
Assert.AreEqual(dto["prop1"], 100);
Assert.AreEqual(dto["prop2"], 200);
}