Methods That Return Values

If you have a method that does generate some value that should be returned, you need to use the Function keyword:

Public Function Age() As Integer

Return CInt(DateDiff(DateInterval.Year, mBirthDate, Now())) End Function

Note that you must indicate the data type of the return value when you declare a function. This example returns the calculated age as a result of the method. You can return any value of the appropriate data type by using the Return keyword.

You can also return the value without using the Return keyword by setting the value of the function name itself:

Public Function Age() As Integer

Age = CInt(DateDiff(DateInterval.Year, mBirthDate, Now())) End Function

This is functionally equivalent to the previous code. Either way, you can use this method with code similar to the following:

Dim myPerson As New Person() Dim age As Integer age = myPerson.Age()

The Age method returns an Integer data value that you can use in the program as required; in this case, you're just storing it in a variable.

0 0

Post a comment