How to create a function with an optional parameter in VB.NET

1 Answer

0 votes
Imports System

Module Program

    ' ------------------------------------------------------------
    ' A function with an optional parameter
    ' ------------------------------------------------------------
    ' The parameter "greeting" is optional because it has a default value.
    ' If the caller does not supply it, "Hello" will be used automatically.
    ' ------------------------------------------------------------
    Function Greet(name As String, Optional greeting As String = "Hello") As String
        Return greeting & ", " & name
    End Function

    ' ------------------------------------------------------------
    ' Main program
    ' ------------------------------------------------------------
    Sub Main()
        ' Calling the function WITHOUT the optional parameter
        Dim result1 As String = Greet("Pickle")

        ' Calling the function WITH the optional parameter
        Dim result2 As String = Greet("Meowzart", "Welcome")

        Console.WriteLine(result1)
        Console.WriteLine(result2)
    End Sub

End Module



' ------------------------------------------------------------
' run:
'
' Hello, Pickle
' Welcome, Meowzart
' ------------------------------------------------------------


 



answered 4 hours ago by avibootz
...