Search code examples
vb.netcolon-equals

What does := mean in VB?


I've been using Visual Studio and I work with VB. Now I've noticed something called text:= in the IntelliSense suggestion list it gives me when coding. I'm not sure what it is. Could anyone explain it to me?


Solution

  • It allows you to specify the value of a particular parameter when passing arguments to a method. Normally, the parameters are determined by the order of the arguments. For instance, if you had a method like this:

    Public Sub WriteStrings(s1 As String, s2 As String)
        Console.AppendLine(s1 & s2)
    End Sub
    

    You would normally just call it like this:

    WriteStrings("A", "B")  ' Outputs "AB" 
    

    However, you could call it with named parameters like this:

    WriteStrings(s1:="A", s2:="B")  ' Outputs "AB" 
    

    In that example, the only real advantage is that it is obvious, when looking at the code, which argument is being passed for each parameter. However, it also allows the interesting possibility of passing the arguments in a different order. For instance:

    WriteStrings(s2:="A", s1:="B")  ' Outputs "BA" 
    

    However, the most common place you'll see it is when the parameters are optional. For instance, when calling this method:

    Public Sub DisplayPerson(Optional includeName As Boolean = True, 
                             Optional includeAge As Boolean = False,
                             Optional includeAddress As Boolean = True)
    

    And you want to leave the default settings for the first two parameters and just want to force includeAddress to be False, you could just call it like this:

    DisplayPerson(, , False)
    

    But that's a little confusing. Many people find it less confusing to specify the name of the parameter to make the code easier to read:

    DisplayPerson(includeAddress:=False)
    

    Since arguments to set the properties of an attribute have no particular order, it's very common to see named arguments used there as well:

    <DataContract(Name:="Test")>