Understanding UDT's (User-Defined Types)

  In VB all variables are declared as a 'type'. Whether it be Integer, String, Variant, etc. But sometimes we may want a combination of different types to be associated with one variable. For instance, if you have a list of books and for each book you want to save the author, the title, and how many pages. You could do this by creating a UDT:

  Private Type Book
      Title As String
      Author As String
      Pages As Integer
  End Type

Then you need to declare your variable as this type:

  Dim vBook As Book 

Now when you want to save the book information you can simply put:

  'I could use a 'With' statement here but
  'to keep it simple for now I won't

  vBook.Title = "The Books Title"
  vBook.Author = "Guy Smiley"
  vBook.Pages = 132

and its the same principle to retrieve values from them:

  Text1 = vBook.Title
  Text2 = vBook.Author
  Text3 = CStr(vBook.Pages)
'convert to a string

Now if I created an array as Type Book (to store a library of books), and wanted to save the info from vBook to that array, I could do it one at a time:

  vBooks(1).Title = vBook.Title
  vBooks(1).Author = vBook.Author
  vBooks(1).Pages = vBook.Pages

but there's an easier way:

  vBooks(1) = vBook

Now when working with UDT's, if at all possible you should set the length of your strings. Fixed length strings will take up less room in memory and can be easier to retrieve if your converting from byte arrays (winsock applications). For instance on our Book Type...say we added a BookCode variable, and we knew that all the codes would be 5 digits long. We could declare it as follows:

  Private Type Book
      Title As String
'dynamic-length (we don't know the length)
      Author As String 'dynamic-length
      Pages As Integer
      BookCode As String * 5
'fixed-length
  End Type

Now there's more to UDT's such as arrays inside your UDT but I'm going to try and cover that in a separate article on arrays. But hopefully this will get you started.

-suprize