Why can I invoke functions without parentheses in VB.NET?

Asked

Viewed 37 times

3

In C#, this code does not compile:

public static string Teste(){
    string val = "";
    return val.Trim;
}

Because the function Teste requires a return of the type string, and Trim is a MethodGroup. That makes perfect sense in my opinion.

However, in VB.NET, this function works perfectly:

Public Function Teste() as String
    Dim valor as String = ""
    Return valor.Trim
End Function

Why does calling functions in VB not need parentheses? Can I pass parameters for functions invoked in this way? After all, there is a difference between calling with or without parentheses?

1 answer

3


I do not know if someone will be able to answer something better than: it is so because it was defined that way. Whoever developed the language thought it was a good idea and decided that once it was done.

Statement of sub procedures also have this, you can create them as Sub Teste or Sub Teste().

I can pass parameters to functions invoked in this way?

No. Parentheses are only optional for functions that do not require parameters (either to declare or to invoke).

Sub Teste           ' Ok, não tem parâmetros, não precisa de parênteses
Sub Teste()         ' Também é correto.
Sub Te(x as String) ' Precisa de parênteses, por causa dos parâmetros

obj.Teste           ' Ok, não tem parâmetros, não precisa de parênteses
obj.Teste()         ' Mas você pode usálos, de qualquer maneira
obj.Te("A")         ' Precisa de parênteses para passar o parâmetro

After all, there is a difference between calling with or without parentheses?

None. This is purely syntax.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.