Using User-Defined Types with procedures

Subroutines, functions, Methods, and Properties can process User-Defined Types as well as any other data type.  This topic covers the following topics:

Passing fields as arguments

Members in User-Defined Types that are one of the built-in PowerBASIC types (INTEGER, WORD, STRING, and so on) can be passed to procedures and functions as if they were simple variables.  For example, given the User-Defined Type PatientRecord, as follows:

TYPE PatientRecord

  FullName  AS STRING * 32

  AmountDue AS DOUBLE

  IdNum     AS LONG

END TYPE

DIM Patient AS PatientRecord

…you could use a procedure PrintStatement:

SUB PrintStatement(Id AS LONG, AmountPastDue AS DOUBLE)

  ' access Id and AmountPastDue

END SUB

…like this:

CALL PrintStatement(Patient.IdNum, Patient.AmountDue)

Passing records as arguments

You can also write your procedures to accept arguments of User-Defined Types.  This is especially useful if you want to pass many arguments; rather than have a long argument list, you can pass a single User-Defined Type.  For example, given the PatientRecord User-Defined Type discussed in the previous section, you could write your PrintStatement procedure as follows:

SUB PrintStatement(Patient AS PatientRecord)

  ' access Patient.IdNum and Patient.AmountDue

END SUB

You'd call PrintStatement like this:

CALL PrintStatement(Patient)

Passing record arrays as arguments

Procedures can accept arrays of records as easily as they can accept arrays of other Types.  For example, if you had an array of PatientRecords, each containing a patient record with an amount due, you could write a function that returns the total amount due for all the patient records in the array:

FUNCTION TotalAmountDue(Patients() AS PatientRecord)

  DIM total AS DOUBLE

  RESET total

  FOR ix = LBOUND(Patients) TO UBOUND(Patients)

    total = total + Patients(ix).AmountDue

  NEXT

  TotalAmountDue = total

END FUNCTION

You might call the function like this:

DIM Patients(1 TO 100) AS PatientRecord

' more code here

x$ = "Total amount due:" + STR$(TotalAmountDue(Patients()))

 

See Also

User-Defined Types (UDTs)

Storage requirements and restrictions

Unions