views:

83

answers:

2

In physics library written in C# I have the following code:

(in ContactManager.cs)

public delegate void PostSolveDelegate(Contact contact, ref ContactImpulse impulse);
public PostSolveDelegate PostSolve;

And an example that uses that code is:

(in Test.cs)

public virtual void PostSolve(Contact contact, ref ContactImpulse impulse)
{
}

ContactManager.PostSolve += PostSolve;

I'd like to do the same in VB. (just thandling the delegate, not the declaration)

I tried this, but it doesn't work:

AddHandler ContactManager.PostSolve, AddressOf PostSolve

The following works, but only allows me to have one handler for the delegate:

ContactManager.PostSolve = new PostSolveDelegate(AddressOf PostSolve)

Is there a way for me to do the same thing in VB that was done in the first piece of code?

Thanks!

+1  A: 

Do you declare the PostSolve as an event in the ContactManager class? You need to declare it as follows:

Public Event PostSolve()

You can't do this AddHandler ContactManager.PostSolve, AddressOf PostSolve because the PostSolve is not an event here, but a delegate.

John Hpa
I edited my post to show the declaration. Unfortunately I can't change it though because it's a separate library.
Homeliss
Then, I think you should do it as daddyman's solution.
John Hpa
+2  A: 

A delegate can be a multicast delegate. In C# you can use += to combine multiple delegates into a single multicast delegate. Usually you see this done as an event and then use AddHandler in VB to add multiple delegates to the event.

But if you did something like this:

Public Delegate Sub PostSolver()

and then declared the field in a class:

Private PostSolve As PostSolver

and then created two delegates and used Delegate.Combine to combine them:

Dim call1 As PostSolver
Dim call2 As PostSolver
call1 = AddressOf PostSolve2
call2 = AddressOf PostSolve3

PostSolve = PostSolver.Combine(call1, call2)

You can call PostSolve() and both delegates will be called.

Might be easier just to make it an Event which is setup to do this without the extra hassle.

Update: To remove a delegate from the list you use the Delegate.Remove method. But you must be careful to use the return value as the new multicast delegate or it will still call the delegate you thought you removed.

PostSolve = PostSolver.Remove(PostSolve, call1)

Calling PostSolve will not call the first delegate.

daddyman
Is this what happens when you call += on the delegate in C#? If so, would I call Delegate.Remove(ContactManager.PostSolver, PostSolver) to remove it from the delegate?
Homeliss
Yes. I updated the answer with an example.
daddyman