Delegate question

  • Thread starter Thread starter Larry Smith
  • Start date Start date
L

Larry Smith

Hi there,

Given a delegate that points to a non-static member function, is there a
cleaner way to change the object instance it's called on other than invoking
"Delegate.CreateDelegate()" (and changing the object instance while leaving
the same member function intact). Thanks in advance.
 
Hi Larry,

Yes, there is.

Delegates that are created using the "delegate" keyword in C# derive from
MulticastDelegate, which derives from Delegate. MulticastDelegate allows a
single delegate to contain an invocation list that consists of multiple
delegates. The delegates in the invocation list are invoked when the owning
delegate is invoked.

Using the multicast feature of delegates you can combine the first delegate
with the new delegate and then remove the first delegate from the list:

static void Test()
{
Console.WriteLine("Test");
}

static void Test2()
{
Console.WriteLine("Test2");
}

delegate void RunTest();

static void Main()
{
// create the delegate instance
RunTest multicastDel = new RunTest(Test);

// add another delegate to the invocation list
multicastDel += new RunTest(Test2);

// If multicastDel() were to be called now, the output would be:
// Test
// Test2

// remove the original delegate
multicastDel -= new RunTest(Test);

multicastDel();
}

Output:

Test2
 
Larry Smith said:
Given a delegate that points to a non-static member function, is there a
cleaner way to change the object instance it's called on other than invoking
"Delegate.CreateDelegate()" (and changing the object instance while leaving
the same member function intact). Thanks in advance.

No - you have to create a new instance, because delegates are
immutable. Using Delegate.CreateDelegate is probably the easiest way of
doing this in a general manner.
 
Hi Jon,
No - you have to create a new instance, because delegates are
immutable. Using Delegate.CreateDelegate is probably the easiest way of
doing this in a general manner.

Right, I forgot that += creates a new instance. My example is pointless :)

Sorry for any confusion, Larry.
 
Given a delegate that points to a non-static member function, is there a
No - you have to create a new instance, because delegates are
immutable. Using Delegate.CreateDelegate is probably the easiest way of
doing this in a general manner.

Ok. Thanks for the info (appreciated)
 
Dave Sexton said:
Hi Jon,


Right, I forgot that += creates a new instance. My example is pointless
:)

Sorry for any confusion, Larry.

No problem. Thanks anyway.
 

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

Back
Top