What is the & operating doing in this situation

Viewed 81

In the function below, what is the meaning of the & character? I'm not aware how it's valid syntax or how this would be used normally.

Normally using &= together would do a concatenation and assignment, resulting in "Hello world". However in this "typo" the code actually compiles but the result is just an assignment of " world" to the MyStr variable. Also if you define MyStr in the function rather than at the class level, the result is that it will not compile and interprets the & as a Type Character and fails because MyStr is a string and not of type Long.

Public Class MyClassName

    Private MyStr As String

    Public Sub New()

    End Sub

    Public Function MyFunction() As String

        MyStr = "Hello"

        MyStr& = " World"

        Return MyStr

    End Function

End Class
3 Answers

Microsoft admits it's a bug in the compiler.

It is not going to be fixed because that would be a breaking change.

As you mention, the & is acting as a type character. Type characters are essentially just a shorthand for declaring the type of a variable. For example, you could use

dim value& = 100 rather than dim value as Long = 100

They are generally used when defining a value on the fly, such as when passing a value to a function:

dim result = funcThatTakesALong(100&)

You can also see in the link that you posted there are also type characters for integers (%), decimals (@), singles (!), doubles (#), and strings ($).

Edit: formatting

I think this may explain the purpose of the operators

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    XYZ(9&) '  Long values
    XYZ(9L)

    XYZ(9I) ' Int32 values
    XYZ(9%)

    XYZ(9S) 'Int16 value

    XYZ("9"c) ' a single charcter
    XYZ("9") '  a string
End Sub

Sub XYZ(ByVal arg As Object)
    Debug.Print("arg type is " & arg.GetType.ToString)

    'do some stuff depends on the type of arg

End Sub

.

Related