Skip to content

Creating objects and arrays

paulbartrum edited this page Apr 26, 2016 · 4 revisions

It is very common in JavaScript to create "property bags", objects with an arbitrary set of properties, like this:

var segment = {
  type: "Feature",
  properties: {},
  geometry: {
    type: "LineString",
    coordinates: [
      [ -37.3, 121.5 ],
      [ -38.1, 122.6 ]
    ]
  }
}

Here's the equivalent C# code to create the same object:

var segment = engine.Object.Construct();
segment["type"] = "Feature";
segment["properties"] = engine.Object.Construct();
var geometry = engine.Object.Construct();
geometry["type"] = "LineString";
geometry["coordinates"] = engine.Array.Construct(
  engine.Array.Construct(-37.3, 121.5),
  engine.Array.Construct(-38.1, 122.6)
);
segment["geometry"] = geometry;
// segment can now be set as a global variable, or passed to a function.

Note: Array.Construct behaves like new Array. Contrary to expectations, new Array(5) does not create a single element array, but instead creates an array with length 5. You can use Array.New instead to get more consistent behaviour, but you must pass in an array (e.g. Array.New(new object[] { 1.0, 2.0 })).

Next tutorial: Using the console API