New
The new
expression is used to instantiate a new Class, Record or dynamic Array type. When instantiating a class use parenthesis, when instantiating an array type use blocks.
// creates a new instance of List<String> and calls the constructor.
var x := new List<String>;
// creates an array of integers with size 15
var y := new int[15];
// creates an array of integers with size 15
var y := MyRecord(5);
For classes and dynamic arrays, calling new
will allocate the necessary space on the heap to store the data on the heap. Since records are stack based, no allocation is necessary, and in fact the use of new
on record types is infrequent.
For both classes and record, the new
expression will also execute one of the type's Constructors.
Parameters
The new
expression can optionally provide zero or more parameters, to the constructor, surrounded by parenthesis. Similar to regular method overloading, a type can provide multiple constructors, and the new
expression will pick the constructor that best matches the provided parameters. The parenthesis are optional (but encouraged) when no parameters are passed.
var x := new MyClass(15); // Calls the constructor with 15
Types may also provide named constructors, typically starting with the prefix with
, that can be used to further disambiguate, which constructor will be called:
var x := new List<String> withCapacity(20);
Property Initializers
Very often, the first task after creating a class instance is to initialize some of its properties that are not set by a constructor. For example:
var b := new Button();
b.Title := 'Click me!';
Oxygene allows to add property initializers as part of the parameter list, to do this in one step. this is especially helpful when the created object is immediately passed on to, say, a method call:
fContriols.Add(new Button(Title := "Click me!");
This extended syntax is only supported for constructors, and the property initializers must be placed after any of the regular constructor parameters.