Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Being able to pass in an argument to a function with no parameters

I'm using VB.NET currently and I've come across an issue. This is my class:

Public class foo

    Private _bar As Integer
    Private _name As String

    Public Sub New(bar As Integer)
        Me._bar = bar
        Me._name = getName(bar) '//Passing in an argument where it is not needed
    End Sub

    Private Function getName() As String

        '//Get name from database using _bar as a lookup(it's essentially a primary key)
        '//Name is obtained successfully (checked when debugging)
        '//Return name

    End Function

End Class

I am able to run this code despite passing in an argument to getName where it has no parameters. However, when I run it, the Me._name field always ends up with an empty string (not a null value as it initially starts out as) but I know that the getNamemethod is returning the correct string as I checked it during debugging. If I remove the unneeded parameter then it works as expected and Me._name gets the returned value.

Why am I able to pass an argument where there shouldn't be one and not get any errors showing up in my error list? I tried this on a coworkers computer and they got a "Too many arguments" error.

like image 631
BenM Avatar asked Jan 11 '23 06:01

BenM


1 Answers

We can call a function/sub with or without parentheses in VB.NET, so this

getName(bar)

is actually the same as this

getName()(bar)

and that's why there's no errors.

Furthermore, getName(bar) won't pass bar as a parameter to getName function, but it will return the (bar+1)th character of the value returned by getName().

For example if we change getName function to this

Private Function getName() As String
    Return "test"
End Function

then getName(1) will be the same as getName()(1) and it will return the second character of "test", which is "e".

like image 122
ekad Avatar answered Jan 30 '23 21:01

ekad