event subscription notification

G

Guest

Hi all

I have a class MyClass that exposes event A. Inside the class, I need to
catch the moment when some other class subscribes to the event A.
In other words, when some other class executes something like

public MyOtherClass()
{
...
MyClass.A += new AEventHandler(MyHandlerA);
}

I need class MyClass to be notified somehow about this.

Any ideas?
Thank you
 
O

Oliver Sturm

Alex said:
I have a class MyClass that exposes event A. Inside the class, I need to
catch the moment when some other class subscribes to the event A.
In other words, when some other class executes something like

public MyOtherClass()
{
...
MyClass.A += new AEventHandler(MyHandlerA);
}

I need class MyClass to be notified somehow about this.

There's a syntax that you should be able to use here:

class MyClass {
AEventHandler myHandlers;
public event AEventHandler A {
add {
myHandlers += value;
// do whatever else you want
}
remove {
myHandlers -= value;
// do whatever else you want
}
}
}



Oliver Sturm
 
N

Nicholas Paldino [.NET/C# MVP]

Alex,

You can use the following syntax (much like property assignments):

public class Test
{
public event EventHandler SomeEvent
{
add
{
// Perform some code before the subscription.
// Add the event.
SomeEvent += value;
// Perform some code after the subscription;
}
remove
{
// Perform some code before the subscription.
// Remove the event.
SomeEvent -= value;
// Peroform some code after the subscription.
}
}
}

Hope this helps.
 
N

Nicholas Paldino [.NET/C# MVP]

Oops, I had an infinite recursion here. Do what Oliver suggested, declaring
the private field.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Nicholas Paldino said:
Alex,

You can use the following syntax (much like property assignments):

public class Test
{
public event EventHandler SomeEvent
{
add
{
// Perform some code before the subscription.
// Add the event.
SomeEvent += value;
// Perform some code after the subscription;
}
remove
{
// Perform some code before the subscription.
// Remove the event.
SomeEvent -= value;
// Peroform some code after the subscription.
}
}
}

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Alex K. said:
Hi all

I have a class MyClass that exposes event A. Inside the class, I need to
catch the moment when some other class subscribes to the event A.
In other words, when some other class executes something like

public MyOtherClass()
{
...
MyClass.A += new AEventHandler(MyHandlerA);
}

I need class MyClass to be notified somehow about this.

Any ideas?
Thank you
 

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