Working WinForms Example
The following example demonstrates overloading a constructor so that you have the option to initialize a property at creation.
Create a form and place a button on it and alter the code as follows:
namespace CR_Constructor;
interface
uses
System.Drawing,
System.Collections,
System.Collections.Generic,
System.Linq,
System.Windows.Forms,
System.ComponentModel;
type
/// <summary>
/// Summary description for MainForm.
/// </summary>
MainForm = partial class(System.Windows.Forms.Form)
private
method button1_Click(sender: System.Object; e: System.EventArgs);
protected
method Dispose(disposing: Boolean); override;
public
constructor;
end;
Cyborg = class(System.Object)
private
public
property CyborgName: String; //Property using implicit syntax.
constructor(); //No parems constructor.
constructor(pName: String); //Constructor with a string parameter.
end;
implementation
{$REGION Construction and Disposition}
constructor MainForm;
begin
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
end;
method MainForm.Dispose(disposing: Boolean);
begin
if disposing then begin
if assigned(components) then
components.Dispose();
//
// TODO: Add custom disposition code here
//
end;
inherited Dispose(disposing);
end;
{$ENDREGION}
method MainForm.button1_Click(sender: System.Object; e: System.EventArgs);
var
MyRobot1: Cyborg;
MyRobot2: Cyborg;
begin
MyRobot1 := New Cyborg;
MyRobot1.CyborgName := "John";
MessageBox.Show("My robot's name is " + MyRobot1.CyborgName + ".");
MyRobot2 := New Cyborg("Cameron");
MessageBox.Show("My robot's name is " + MyRobot2.CyborgName + ".");
end;
//Constructor with no parems.
constructor Cyborg();
begin
end;
//Constructor with a string parameter.
constructor Cyborg(pName: String);
begin
CyborgName := pName;
end;
end.
Use the Legacy Create Constructor
If you turn on legacy support for Create, you can use the Delphi-style Create to instantiate objects instead of New:
var
MyRobot1: Cyborg;
begin
MyRobot1 := Cyborg.Create;
T1.CyborgName := "John";
//...
end;
To turn on legacy support for Create, in the solution explorer right click on your solution or project and select Properties. On the Compatibility tab, check Allow 'Create' Constructor calls.
