A Simple Example
The following example uses our class above. Notice for the static member, you can use either an instance reference (a variable), or the type name (the class name. That's why static members are sometimes referred to as class members. Static members belong to the class and you can reference by the class name.
Note: In Prism, you can refer to static members using an instance or class type. In VB.Net you get a warning and in C# you get a compiler error. My preferred usage is to stick with the class type (the class name).
namespace CR_StaticMembers;
interface
uses
System.Drawing,
System.Collections,
System.Collections.Generic,
System.Linq,
System.Windows.Forms,
System.ComponentModel;
type
///
/// Summary description for MainForm.
///
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
FSerialNumber: String:="A100";
public
FCyborgName: String;
FCyborgAge: Integer:=0;
class SeriesID: Integer:=100; readonly;
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);
begin
//Read static member field BEFORE we create our object.
//Notice the use of the class name, not an object name.
MessageBox.Show("We will now build a series " + Cyborg.SeriesID + " robot.");
var MyRobot := New Cyborg;
MyRobot.FCyborgName := "John";
MyRobot.FCyborgAge := 34;
MessageBox.Show("We created a " + MyRobot.FCyborgAge + " year old robot named " + MyRobot.FCyborgName + ".");
//You can refer to static members using an instance.
//(in VB.Net you get a warning, in C# you get a compiler error).
MessageBox.Show("A series " + MyRobot.SeriesID + " robot.");
//However, my preferred usage is to stick with the class name.
MessageBox.Show("A series " + Cyborg.SeriesID + " robot.");
end;
end.
Note: The public member fields FCyborgName and FCyborgAge are used here for demonstration only. You normally want to make them private and access them via a member property. Also note that SeriesID starts with an uppercase "S" instead of the customary "F" because SeriesID behaves similar to a read-only properity.