New (keyword)

From The Oxygene Language Wiki
Jump to: navigation, search

This is a Language topic about Oxygene
 

Language Topics Introduction | Structured Overview | Grammar | Keywords | Functions



The "new" operator

Similar to C#, new class instances are instantiated using the new keyword:

MyClass := new BaseClass(...);

For backward compatibility, Oxygene supports the ".Create" constructor:

MyClass := BaseClass.Create(...);

It is recommended that you use 'new' whenever possible though.


Inline Declaration

A class can be instantiated inline as a local variable and even within the interface section:

type
  MainForm = class(System.Windows.Forms.Form)
  {$REGION Windows Form Designer generated fields}
// lines omitted
  {$ENDREGION}
  protected
    method Dispose(aDisposing: boolean); override;
  public
    constructor;
    class method Main;
  private
  var
    StringQueue: Queue<String> := new Queue<String>;
    StringStack: Stack<String> := new Stack<String>;
    IntegerQueue: Queue<Integer> := new Queue<Integer>;
    IntegerStack: Stack<Integer> := new Stack<Integer>;
  end;

Note: see Type Inference, which allows the following simpler code:

var
    StringQueue := new Queue<String>;
    StringStack := new Stack<String>;
    IntegerQueue := new Queue<Integer>;
    IntegerStack := new Stack<Integer>;
  end;


Using Class Instances

Inline declarations are possible because of the .NET garbage collection mechanism (see Finalizers), but there are classes that own other resources that need disposing. If a class implements IDisposable, then instantiate your class via 'using', which implicitly calls IDisposable.Dispose, e.g.:

using lWriter: StreamWriter := new StreamWriter(lFile) do begin
      fFiles.Add(lWriter);

      lWriter.WriteLine('#EXTM3U');

      for f: string in lFiles do begin
        if Path.GetExtension(f) = '.mp3' then begin
          lFilename := fPrefix+f.SubString(length(fMusicFolder));
          for w: StreamWriter in fFiles do begin
              w.WriteLine(lFilename);
          end;
        end;
      end;


Named Parameters

Oxygene supports the use of named parameters in a constructor call to set field or property values. This allows you to set values on a property without having to declare a variable:

type
  Person = class
  public
    constructor; empty;
    
    property Name: string;
  end;

Persons.Add(new Person(Name := 'John'));


See Also

Personal tools
Namespaces

Variants
Actions
Navigation
Getting Started
Sections
If you know
More
Toolbox