dotnet / dotnet/vblang

Surprising syntax rule about invoking a delegate defined as a property.

Open
#243 17 comments 0 reactions 0 assignees View on GitHub
Dominant language
No language data
Stars
328
Forks
71
PR merge metrics
No merged PRs in 30d

Description

Consider the following:

```vb
Public Class CTest
Public Action1 As Action(Of Action)

Public Property Action2 As Action(Of Action)

Public Function Action3() As Action(Of Action)
End Function

Public Sub Test()
'this is OK. Action1 is just a field.
Me.Action1(Sub() Console.WriteLine("blah"))

'this FAILS. Action2 has same type as Action1 but is now a property.
'Compiler says: TOO MANY ARGUMENTS TO Action2
Me.Action2(Sub() Console.WriteLine("blah"))

'this is WHAT THE COMPILER WANTS (notice the double brackets after Action2).
Me.Action2()(Sub() Console.WriteLine("blah"))

'I expect to use brackets here because Action3 is a function.
Me.Action3()(Sub() Console.WriteLine("blah"))

Me.Action2 = Nothing '<--- this I expect and do all the time.
Me.Action2() = Nothing '<--- this works but is just weird!
End Sub
End Class
```

The comments spell it out but the special point of interest is the line:

```vb
Me.Action2(Sub() Console.WriteLine("blah"))
```

The `Action1` field and the `Action2` property have identical types (i.e `Action(Of Action)`). I was initially using the field form in my code which allows me to invoke the delegate as follows:

```vb
Me.Action1(Sub() Console.WriteLine("blah"))
```

...but later I decided to use a property, so I added the `Property` keyword (resulting in a declaration similar to `Action2`), but now all the call sites invoking the delegate were broken and the compiler wanted code like this:

```vb
Me.Action2(Sub() Console.WriteLine("blah")) '<-- CALL THIS FORMAT 1
```

...to be written like this (i.e put empty brackets immediately after the property name):

```vb
Me.Action2()(Sub() Console.WriteLine("blah")) '<-- CALL THIS FORMAT 2
```

Is there any reason that format 1 above can't work until the compiler requires format 2?

Also how is this legal syntax:

```vb
Me.Action2() = Nothing '<--- this works but is just weird!
```
...? It looks like calling a function and then nulling its result (it's impossible to write a function that would allow this today without VB support for [ref returns](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/ref-returns)).

CC: @AnthonyDGreen

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.