Fields
From The Oxygene Language Wiki
This is a Language topic
Feel free to add your notes to this topic below.
Fields are vars (variables) that hold data for the class. The data is stored in the class instance provided that it is not a class var, in which case there is a shared single copy and you don't then even need to instantiate the class.
You can place fields at the start of any visibility section (a default var is assumed) or anywhere following a var or class var directive.
Specifying a field as read-only is supported (i.e. immutable) and its value can only be set in the class constructor. Fields can also be used to implement interfaces.
Syntax examples:
type MyClass = class private fField1: Integer; fField2: Integer := 5; fField3: Integer; readonly; fField5: SomeClass; implements ISomeInterface; fField6: Hasttable := new Hashtable(); var fField4: String; fField5: double; class var fClassField1: String; fClassField2: Double := 5; ... end;
Fields may be placed anywhere within the class declaration - they do not have to precede methods and properties. While you might want to declare them first, an alternative is to group them with methods and properties with the same visibility:
type MyClass = class private fField1: Integer; method PrivMethod; protected fField2: Integer := 5; method ProtectMethod; end;
Field Initialization
The time that a constructor initializes its fields is important and this can occur before or after the call to an inherited constructor.
Fields are normally initialized before calling the inherited constructor, with the following three exceptions:
- if the field uses SELF directly
- when the field accesses field(s) of the ancestor class
- when a field calls a method of the current class
See Constructors for more information.
Notes
Immutable fields can be preferable to the use of constants. The latter are linked at compile time, so if you have assembly1, which defines a const and then build assembly2 which uses the const, the constant value will get linked directly into the IL code of assembly2. If you now go and change the value in assembly1, assembly2 will keep using the old value until you rebuild it.
Immutable fields, on the other hand, are fields like any others. When assembly2 accesses the field, it is really accessing the assembly1's field.
See Also
Area: Oxygene Language
Compiler version: Oxygene 5
Language Glossary — Keywords — Types — FAQ — How To