Reputation: 872
I have the following function definition:
Function Parameterless() as String
There are no overrides or overloads of it. The following line will happily compile and run:
Dim s as String = Parameterless(1)
What is going on?
Upvotes: 3
Views: 252
Reputation: 460
I tried replicating it based on your code
Private Function Parameterless() As String
Return "abcd"
End Function
I added a button
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim per As String = Parameterless(1)
TextBox1.Text = per
End Sub
the output displayed on the textbox: b
so the number param there will determine the index number of characters to be displayed
Upvotes: 1
Reputation: 478
"Default" Do this trick
Public Class User
Default ReadOnly Property Number(i As Integer) As String
Get
If i = 1 Then Return "Mark"
Return "Bob"
End Get
End Property
End Class
Private Function TestFunction () As User
Return New User
End Function
So output will be
TestFunction(1) 'Mark
TestFunction(2) 'Bob
Upvotes: 1
Reputation: 460028
What happens here is indeed strange and a VB.NET oddity.
Both, methods and indexers, are called with ()
(as opposed to C# where you use []
for the latter). Because of downwards compatibility these parentheses aren't mandatory. You can call any method that doesn't take any parameters without. So you can use:
Dim s As String = Parameterless
and you can use (recommended for this reason)
Dim s As String = Parameterless()
But why you can use Parameterless(0)
even if there is no overload? Because the method returns a String
which has an indexer. So if you want the first character of the returned string you could either use (recommended):
Dim firstLetter As Char = Parameterless()(0)
or (not recommended but your case)
Dim firstLetter As Char = Parameterless(0)
This works because there is no overload and the VB.NET compiler decides that you want to call the method without parameters and then you want to use the indexer on the string.
If the method would not return a string (or any other type that has an indexer) but for example an integer you would get a compiler error.
Upvotes: 8