Visual Basic/Data Types/User Defined

From Wikibooks, open books for an open world
< Visual Basic | Data Types
Jump to: navigation, search

VB makes it possible to create user defined data types by means of the statement Type

[edit] Possible uses

Although VB has a rich variety of native data types like booleans, strings, doubles etc. it is impossible to think of everything. Take for example complex numbers and quaternions. These are mathematical objects (numbers actually) that obey certain rules of addition and multiplication.

For example a complex number has a real and an imaginary component

Z = re + im.i

A quaternion has three different imaginary components

H= a + b.i + c.j + d.k

It is possible to make your own complex numbers or quaternions by writing:

Type Complex
re as Double
im as Double
End Type

Or:

Type Quat
s as Double
i as Double
j as Double
k as Double
End Type

It is advisable to add a Option explicit statement, this avoids a lot of confusion between various types.

From now on you can treat these types as if they were native, but of course you will have to define functions to actually do something useful with them. Adding two complex numbers or quaternions means that you add the various parts separately:

Function AddQuat(a As Quat, b As Quat) As Quat
AddQuat.s = a.s + b.s
AddQuat.i = a.i + b.i
AddQuat.j = a.j + b.j
AddQuat.k = a.k + b.k
End Function

Multiplying two quaternions is bit more involved, but this works fine:

Function MultQuat(a As Quat, b As Quat) As Quat
MultQuat.s = a.s * b.s - a.i * b.i - a.j * b.j - a.k * b.k
MultQuat.i = a.s * b.i + a.i * b.s + a.j * b.k - a.k * b.j
MultQuat.j = a.s * b.j + a.j * b.s + a.k * b.i - a.i * b.k
MultQuat.k = a.s * b.k + a.k * b.s + a.i * b.j - a.j * b.i
End Function
Personal tools
Namespaces
Variants
Actions
Navigation
Community
Toolbox
Sister projects
Print/export