COMPARISONS

ARRAY CLASS HASH STRUCT

Compare four ways to group values

Description

An array, an object, a hash and a structure all group values. They differ in access, types, copying and where they may be used.

ARRAYCLASSHASHSTRUCT
Accessby position: a[ 2 ]by member: o:nameby key: h[ "name" ]by field: st.name
Membersadded and removed at run timeDATA declared in the classadded and removed at run timefields declared in STRUCT
Value typesany, mixedany; DATA with AS has a fixed typeany, mixeda fixed type per field, checked by the compiler
Assignment b := ab and a share one arrayb and a share one objectb and a share one hashb and a share one structure
CopyAClone( a )noneHClone( h )SClone( st )
Where it may be usedanywhereanywhereanywhereanywhere
Holds a code blockyesyesyesyes, in a CODEBLOCK field
Goes to a DLLnononoyes, with @, only with fields of C types

Use an array for values in order. Use a hash for values found by key. Use a class for data with its own methods. Use a structure for a fixed set of typed values, such as the settings of a program, and for a block of memory passed to a DLL.

Notes

A structure is an array that looks different: its fields have names and types. The fields of C types have the C layout. A nested structure lies inside its structure; as a whole it is not a value.

Example

ARRAY_CLASS_HASH_STRUCT.prg
STRUCT Point
   x AS INT32
ENDSTRUCT

CREATE CLASS Counter
   DATA value INIT 1
ENDCLASS

PROCEDURE Main()

   LOCAL aFirst := { 1 }
   LOCAL aSecond
   LOCAL oFirst := Counter()
   LOCAL oSecond
   LOCAL hFirst := { "value" => 1 }
   LOCAL hSecond
   LOCAL stFirst AS Point
   LOCAL stSecond AS Point

   aSecond := aFirst
   aSecond[ 1 ] := 2
   QOut( "ARRAY ", aFirst[ 1 ] )

   oSecond := oFirst
   oSecond:value := 2
   QOut( "CLASS ", oFirst:value )

   hSecond := hFirst
   hSecond[ "value" ] := 2
   QOut( "HASH  ", hFirst[ "value" ] )

   stFirst.x := 1
   stSecond := stFirst
   stSecond.x := 2
   QOut( "STRUCT", stFirst.x )

   RETURN

Output

See also