17

We have this method call:

SendAck(AppData:=AppData, Status:=Status, StatusMessage:=StatusMessage, IsApplication:=IsApplication)

And here is the definition:

Private Sub SendAck(ByVal AppData As XDocument, ByVal Status As Boolean, ByVal StatusMessage As String, ByVal IsApplication As Boolean)

Why does the call have the parameters with the ":=". I'm just curious.

moodymudskipper
  • 46,417
  • 11
  • 121
  • 167
Scott
  • 2,143
  • 2
  • 19
  • 25

2 Answers2

24

The ":=" in VB.Net is used to pass a function argument by name. The default is by position. It allows for parameters to be called in any order and determines the positioning based on name matches.

For example

Sub Example(ByVal param1 as Integer, ByVal param2 As Integer) 
  Console.WriteLine("{0} - {1}", param1, param2)
End Sub

Example(param2:=42, param1:=1) ' Prints "1 - 42"
Example(42, 1)                 ' Prints "42 - 1"
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • Gotcha. Just out of curiosity, when would you want to do this? If you do this to skip certain parameters, why wouldn't you just make them optional? – Scott Oct 29 '10 at 20:16
  • 1
    @Scott, my favorite reason is to make boolean parameters more readable. `GetFiles(true)` is a lot less readable than `GetFiles(recurseIntoSubDirectories := true)` – JaredPar Oct 29 '10 at 20:17
  • 2
    It can also be useful when there is an ugly interface with a huge list of optional parameters, but you only want to specify one that is toward the end of the list. Also sometimes it can help to avoid any ambiguity when there are multiple overloads that involve base classes; naming a parameter when you call the function can remove that. – Andrew Barber Oct 29 '10 at 20:24
  • It is also used to set attribute parameters; any public read / write property on an object that derives from `System.Attribute` can be an attribute constructor parameter, even if there is no defined constructor that contains the parameter. See the example here: https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/concepts/attributes/creating-custom-attributes – ajw170 Mar 09 '23 at 20:10
7

That syntax is using named arguments; Specifying the names of the parameters being set before the := then the value after. Doing that can enable you to skip parameters or do them in different order.

Andrew Barber
  • 39,603
  • 20
  • 94
  • 123