AddressOf doesn't work with if operator

M

Marco Segurini

Hi all,

is there someone that may explain why the VB compiler report an error
for this code?

thanks a lot
Marco.

Module Module1

Sub fn1()
End Sub

Sub fn2()
End Sub

Sub Main()
Dim if_fn1 As Object = If(True, AddressOf fn1, AddressOf fn2)
' error BC30491: Expression does not produce a value
End Sub

End Module
 
A

Armin Zingler

Am 03.12.2010 10:30, schrieb Marco Segurini:
Hi all,

is there someone that may explain why the VB compiler report an error
for this code?

thanks a lot
Marco.

Module Module1

Sub fn1()
End Sub

Sub fn2()
End Sub

Sub Main()
Dim if_fn1 As Object = If(True, AddressOf fn1, AddressOf fn2)
' error BC30491: Expression does not produce a value
End Sub

End Module

This is not an issue with the If operator. Doesn't work also:

Dim o As Object = AddressOf fn1

AddressOf itself does not produce a value. You may want to create a Delegate:

Dim o As Object = New System.Windows.Forms.MethodInvoker(AddressOf fn1)
 
M

Marco Segurini

Am 03.12.2010 10:30, schrieb Marco Segurini:











This is not an issue with the If operator. Doesn't work also:

   Dim o As Object = AddressOf fn1

AddressOf itself does not produce a value. You may want to create a Delegate:

Dim o As Object = New System.Windows.Forms.MethodInvoker(AddressOf fn1)

Sorry, you are true.

the real code is:

Sub Main()
' this works ...
'Dim if_fn2 As System.Action = AddressOf fn1
'if_fn2()
' but this doesn't
Dim if_fn1 As System.Action = If(True, AddressOf fn1,
AddressOf fn2) ' error BC30491: Expression does not produce a value.
End Sub

Marco.
 
A

Armin Zingler

Am 03.12.2010 17:53, schrieb Marco Segurini:
Sorry, you are true.

the real code is:

Sub Main()
' this works ...
'Dim if_fn2 As System.Action = AddressOf fn1
'if_fn2()
' but this doesn't
Dim if_fn1 As System.Action = If(True, AddressOf fn1,
AddressOf fn2) ' error BC30491: Expression does not produce a value.
End Sub

You're right. There seems to be a special assigment behavior. I've looked
for it described in the VB language specificaion but didn't find anything that
describes this behavior. So, the AddressOf operator itself does not produce
a value, it depends on how it is used - which seems to be an exception to how
expressions work in general. Or why else does

Dim o1 As System.Action = AddressOf fn1

work, while

Dim o1 As Object = AddressOf fn1

does not? An Object variable should be able to accept any kind of object,
but this more flexible assignment is not allowed whereas the limitting version works.
Not a consistent behavior, IMO.

So, only this seems to be left:

If(True, New Action(AddressOf fn1), New Action(AddressOf fn2))
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top