Jordan Robins Jordan Robins - 23 days ago 6
Vb.net Question

Indexing the return value of a parameterless function

I've recently come across what I believe to be quite an obscure language feature while writing some vb.net code.

The feature is that if the function that you are calling does not receive any parameters and you attempt to call it with a parameter (And expect to see an error appear, or at least be given a compile time error!), it will get implicitly converted to an attempt to index the return value of the function instead.

The below code example is from a new vb.net form project created in visual studio.

Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load

Call GetCaption()


Me.Text = GetCaption() ' The caption of the form is 'this is my new form'

Me.Text = GetCaption(1) ' The caption of the form is 'h'

Me.Text = GetString(2) 'The caption of the form is '2'
End Sub

Private Function GetCaption() As String
Return "This is my new form"
End Function

Private Function GetString() As String()

Dim x As String() = {"", "0", "2"}

Return x

End Function
End Class


I have found the following documentation that mentions that 'If there are no arguments, you can optionally omit the parentheses. However, using the parentheses makes your code easier to read.' Available Here: https://msdn.microsoft.com/en-gb/library/1wey3ak2.aspx

I have also found documentation about the error that you receive when you try to attempt to this with a function that has a return type that cannot be indexed here: https://msdn.microsoft.com/en-us/library/y1wwy0we(v=vs.140).aspx

I cannot however find any documentation that discusses this functionality, or that mentions the implicit conversion to indexing the function return, instead of attempting to pass parameters to a function that doesn't receive any.

Any ideas?

Answer

You are not calling it with a parameter. The compiler knows the method doesnt take an argument, so it doesnt try to pass it as such. The return of GetCaption() is a string, and a string is a character array which can be indexed so the code is fetching the Nth character from the returned string. Equivalent methods would be:

Me.Text = GetCaption(1)   ' second char, arrays are zero based
Me.Text = GetCaption.Chars(1)   
Me.Text = GetCaption.ElementsAt(1)

Those implement the VB-ism of being able to omit function parens; including them makes it a bit clearer that the code is actually indexing the return value:

Me.Text = GetCaption()(1) 
Me.Text = GetCaption().Chars(1)   
Me.Text = GetCaption().ElementsAt(1)

In the end, the title is correct: the code is indexing the return value. There is no error because strings can be indexed.