Overloading and Delegates

Jarod

Regular
Joined
Feb 5, 2003
Messages
82
Location
Bruxelles
I have a syntax problem
Say I have 3 object:
Visual Basic:
Public Class Class1
End Class

Public Class class2
End Class

Public Class class4
  Public Function myFunctionToCall(ByVal A As String, ByVal B As Class1) As String
  End Function
End Class
and two delegates
Visual Basic:
Public Delegate Function myDelegate1(ByVal A As String, ByVal B As Class1) As String
Public Delegate Function myDelegate2(ByVal A As String, ByVal B As class2) As String
so class4.myFunctionToCall signature fit the signature of myDelegate1 (and not of myDelegate2 because of the second parameter)

Now say I want to use those delegates in an another class:
Visual Basic:
Public Class class3

  Private m_Class4 As class4

  Public Sub New()
    m_Class4 = New class4()
  End Sub

  Public Overloads Function DelegateCall(ByVal myDelegate As myDelegate1, ByVal B As Class1) As String
    Return myDelegate.Invoke("AA", B)
  End Function

  Public Overloads Function DelegateCall(ByVal myDelegate As myDelegate2, ByVal B As class2) As String
    Return myDelegate.Invoke("AA", B)
  End Function

  Public Sub myTest()
    DelegateCall(AddressOf Me.m_Class4.myFunctionToCall, New Class1())
  End Sub

End Class
So I have in that class two overloaded functions which will call either the delegate1, or the delegate 2
However, this doesn't compile with the following error :
"Reference to a non-shared member requires an object reference"
on the addressof in myTest method

If I comment my second overloaded DelegateCall function, it compile.

But I can't see the error ! The two overloaded functions have perfectly different signature and so there is nothing ambigous here.
Any idea ?
 
I think you should be passing New myDelegate1(AddressOf m_Class4.myFunctionToCall) instead of just the AddressOf as you are doing.
 
Ok you're right, it works like this

However I wonder something.
I agree that in IL all the delegates are "converted' into classes, and so it'is normal to pass new instance of those "classes" as parameter to a function.
But I have seen often (even in books) using directly addressof instead of writing new myDelegate(addressof...)
And it works most of times.

So I would like to know in which case we need to use one or the other syntax ? Is there one which is more performant ?
 
Where have you seen just using AddressOf on its own? The only instance I can think of is the VB AddHandler and RemoveHandler methods which perform some magic to save you the trouble of instantiating the correct event handler like C# devs have to.
 
Just take my example and remove the second DelegateCall and it works perfectly just with the addressof !
And for a book example, "Professional VB.NET 2nd edition" at WROX uses such an example
(be sure that I also saw other books giving the "correct" syntax with New MyDelegate(..)
 
Back
Top