event and delegate

T

TonyJ

Hello!

Assume I have a declared a delegate and an event with that delegate type.
We can assume this class is called Test.

Now to my question when this event will be fired must this be done within
the same class which is Test where the event is declared?

//Tony
 
P

Peter Duniho

Assume I have a declared a delegate and an event with that delegate type.
We can assume this class is called Test.

Now to my question when this event will be fired must this be done within
the same class which is Test where the event is declared?

That depends on what you mean. Only that class will have access to the
implicit field that represents the event itself, which is needed to
actually invoke (raise) the event. In that sense, yes...it can only be
done from the same class where the event is declared.

But, you can easily provide a public method that does that work, and thus
call the method from anything that has access to that method. So the
impetus for raising the event need not occur internally to the class.

Pete
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,


It depends of how you declared your delegate and your event. If you declare
them public then other methods outside the class can be wired to the event.
The event can ONLY be directly invoked from inside the class. If you provide
a public method it can also be invoked from the outside.
Take a look at the code below:
public delegate void D();
class C1
{
public void M1()
{
Console.WriteLine("M1");
}
}
class C
{
public event D DEvent;
public void doit()
{
if (DEvent != null)
DEvent();
}
}

C c = new C();
C1 c1 = new C1();
c.DEvent+=new D(c1.M1);
c.DEvent(); // ERROR: The event 'ConsoleApplication6.C.DEvent'
can only appear on the left hand side of += or -= (except when used from
within the type 'ConsoleApplication6.C') C:\best
doctors\ConsoleApplication6\ConsoleApplication6\Program.cs 169 15
ConsoleApplication6
c.doit();
 

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