Union
Declares a union user defined type.
Syntax
`
Union typename
fieldname as datatype
Declare member function declaration ...
...
End Union
`
Parameters
`typename`
Name of the `Union`
`fieldname`
Name of a data field member
`member function declaration`
Any of the supported member functions
Description
Unions are similar to a `Type` structure, except that the elements of a union occupy the same space in memory. The size of the Union is the size of the largest data item. A data item can be an unnamed `Type` . Since they occupy the same space, only a single element can be used.
Unnamed unions can be nested inside a type structure and unnamed types can be nested inside an union . See Example.
Unions support member functions including `Constructor`, `Destructor`, `Function`, `Operator`, `Property` and `Sub`. All members of a union are public and access control is not supported.
A `Union` can be passed as a user defined type to overloaded operator functions.
Example
`
'define our union
Union AUnion
a As UByte
b As Integer
End Union
'define a composite type
Type CompType
s As String * 20
ui As Byte 'Flag to tell us what to use in union.
Union
au As UByte
bu As Integer
End Union
End Type
'Flags to let us know what to use in union.
'You can only use a single element of a union.
Const IsInteger = 1
Const IsUByte = 2
Dim MyUnion As AUnion
Dim MyComposite As CompType
'Can only set one value in union
MyUnion.a = 128
MyComposite.s = "Type + Union"
MyComposite.ui = IsInteger 'Tells us this is an integer union
MyComposite.bu = 1500
Print "Union: ";MyUnion.a
Print "Composite: ";
If MyComposite.ui = IsInteger Then
Print MyComposite.bu
ElseIf MyComposite.ui = IsUByte Then
Print MyComposite.au
Else
Print "Unknown type."
End If
Sleep
`
Dialect Differences

- Object-related features as functions defined inside the `Union` block are supported only in the -lang fb dialect.
- Not available in the -lang qb dialect unless referenced with the alias `__Union`.

Differences from QB

- New to FreeBASIC

See also

- `Type`