Visual Basic.NET 2008 > Programming Fundamentals

Functions Returning Structures - Visual Basic 2008

Suppose you need a function that returns a customer's savings and checking account balances. So far, you've learned that you can return two or more values from a function by supplying arguments with the ByRef keyword. A more elegant method is to create a custom data type (a structure) and write a function that returns a variable of this type.

Here's a simple example of a function that returns a custom data type. This example outlines the steps you must repeat every time you want to create functions that return custom data types:

  1. Create a new project and insert the declarations of a custom data type in the declarations section of the form:

    Structure CustBalance

    Dim SavingsBalance As Decimal
    Dim CheckingBalance As Decimal

    End Structure

  2. Implement the function that returns a value of the custom type. In the function's body, you must declare a variable of the type returned by the function and assign the proper values to its fields. The following function assigns random values to the fields CheckingBalance and SavingsBalance. Then assign the variable to the function's name, as shown next:

  3. Function GetCustBalance(ID As Long) As CustBalance

    Dim tBalance As CustBalance
    tBalance.CheckingBalance = CDec(1000 + 4000 * rnd())
    tBalance.SavingsBalance = CDec(1000 + 15000 * rnd())
    Return(tBalance)

    End Function

  4. Place a button on the form from which you want to call the function. Declare a variable of the same type and assign to it the function's return value. The example that follows prints the savings and checking balances in the Output window:

    Private Sub Button1 Click(...) Handles Button1.Click

    Dim balance As CustBalance
    balance = GetCustBalance(1)
    Debug.WriteLine(balance.CheckingBalance)
    Debug.WriteLine(balance.SavingsBalance)

    End Sub

The code shown in this section belongs to the Structures sample project. Create this project from scratch, perhaps by using your own custom data type, to explore its structure and experiment with functions that return custom data types. In Chapter, "Building Custom Classes," you'll learn how to build your own classes and you'll see how to write functions that return custom objects.

Table of Contents

     
 
W3computing.com Copyright 2011 © All Rights Reserved
 
  Home | Useful links | Contact us