.NET Array Dictionary List String Sub ArrayList Cast Class Console Dates DataTable DateTime Enum File For Format If IndexOf Lambda LINQ Nothing Parse Process Property Regex Replace Select Sort Split StringBuilder Substring

Function. A Function returns a value. It uses a special syntax form in the VB.NET language. The Function optionally accepts one or more parameters—these are called formal parameters. A Function is part of a Module, Class or Structure.Module

Tip:A Function is called from other Functions, Subs or Properties. It can be reused throughout a program.

Example. This is a simple example program that shows the Function keyword. We provide an Area Function: this Function receives a radius. It returns a Double that is the area of a circle with that radius. Its body is only one line long.

Formal parameter:Area receives one formal parameter of type Double. Specifying the type of the parameter is optional but advised.

Returns:The Function returns a value of type Double. After the formal parameter list, the keywords "As Double" indicate the return type.

Based on: .NET 4.5

VB.NET program that demonstrates Function

Module Module1

    ''' <summary>
    ''' Get area of a circle with specified radius.
    ''' </summary>
    Function Area(ByVal radius As Double) As Double
	Return Math.PI * Math.Pow(radius, 2)
    End Function

    Sub Main()
	Dim a As Double = Area(4.0)
    End Sub

End Module


Functions vs. Properties. What is the difference between a Function and a Property? A Property is a type of Function. The Get part of a Property can be implemented as a Function. A Property is a special kind of Function.
Properties are meant to replace getters and setters. So if you have a Sub that simply sets a value, it can be changed to be a Property. And if you have a Function that returns a value, it too can be changed.

Tip:At the level of the implementation, Properties are similar to Functions and Subs.


And:If you want to, you can change all Properties on your types to Functions and Subs. You won't get in trouble for doing this.

But:On existing types, such as those in the .NET Framework, you must use the Property syntax if the member is a Property.

I have programs that I use regularly but don't share with others. I avoid Properties in my custom code: this is because the syntax doesn't help my understanding of the code. It just adds more keywords and makes my life harder.
Return values. A Function can only return one value. But if this value is a class or Structure, like a Tuple or KeyValuePair, it can return many values in this step. The ByRef keyword can be used to set output parameters.Multiple Return Values
Summary. A Function is just like a Sub, except it returns a value. And a Function must return this value—if we have no return value, we need to use a Sub instead. In an expression, a Function's result can be assigned to a Dim.