As I was browsing, I noticed many similar questions from years ago. Let's kick off this discussion with a simple JavaScript example showcasing how easy it is to modify, read, and write properties in objects using this language.
Take a look at the code snippet below:
const dynamicObject = {
a: [1, 2],
b: "String val",
c: 10,
d: { sa: 1, sb: null, sc: [1, 2, 3] }
};
// Adding new properties
const newProp = "e";
dynamicObject[newProp] = "New val";
dynamicObject.f = false;
dynamicObject["d"]["sd"] = null
dynamicObject["d"].se = null
// Modifying properties
const prop = 'a'
dynamicObject[prop].push(3)
dynamicObject.b += " ABCD"
// Modifying child properties of another property
dynamicObject.d.sb = ["New", "Array"]
dynamicObject.d["sa"] += 5
dynamicObject["d"]["sa"] += 5
// Reading properties
const propValue = dynamicObject[prop]
console.log(propValue)
const propValueString = dynamicObject.b
console.log(propValueString)
See the live results here
I attempted to replicate this method using C#:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
dynamic dynamicObject = new {
a = new int[] {1, 2},
b = "String val",
c = 10,
d = new { sa = 1, sb = "abv", sc = new int[] { 1, 2, 3 } }
};
var DO = (IDictionary<string, object>)dynamicObject;
// Adding new properties
const string newProp = "e";
dynamicObject[newProp] = "New val";
dynamicObject.f = false;
dynamicObject["d"]["sd"] = null;
dynamicObject["d"].se = null;
// Modifying properties
const string prop = "a";
dynamicObject[prop].push(3);
dynamicObject.b += " ABCD";
// Modifying child properties of another property
dynamicObject.d.sb = new string[] { "New", "Array" };
dynamicObject.d["sa"] += 5;
dynamicObject["d"]["sa"] += 5;
// Reading properties
object propValue = dynamicObject[prop];
object propValueString = dynamicObject.b;
string result = JsonConvert.SerializeObject(dynamicObject);
Console.WriteLine(result);
}
}
.Net Fiddle example here
However, it doesn't produce the expected output as we're dealing with a strongly typed language like C#. Let's not dwell on this difference for now.
Does C# offer any structures, objects, or libraries that make managing object manipulations as easy as in JS?