Am 03.12.2010 17:53, schrieb Marco Segurini:
> On 3 Dic, 12:36, Armin Zingler <az.nos...@freenet.de> wrote:
>> 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)
>>
>> --
>> Armin
>
> 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))
--
Armin
|