New to c# - events & delegates

T

Trevor

Hello,

How can I setup an event in C#? I would like for class A to have an
event, and class B to intercept the event. Class B should not be able to
call the event itself, only class A. How is this achieved in C# ? Are
there any sample/tutorial projects which do just what I am asking?
 
N

Nicholas Paldino [.NET/C# MVP]

Trevor,

Check out the section of the .NET framework documentation titled
"Handling and Raising Events", located at (watch for line wrap):

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconevents.asp

For information on how to consume events, check out the "Consuming
Events" section. For information on how to raise events, check out the
"Raising and Event" section.

Also, by default, events declared on a class can only be raised by the
class itself. Even derived types can not fire the event.

Hope this helps.
 
E

Eric Newton

say for example you have a System.Windows.Forms.Button instance and it has a
Click event, you can define the event handler as follows:

Button1.Click += new EventHandler(Button_Click);

void Button_Click(object sender, EventArgs e)
{
}

note that the method signature for "Button_Click" must match the
EventHandler's signature (object,EventArgs) and it'll hook up the event at
runtime.

of note, you mentioned "intercepting" an event... you cannot really
"intercept" per se... if an event is subscribed to, its impossible (ie, non
deterministic) to know the order of whos gonna get first dibs to run

perhaps when you said "intercept" you meant "subscribe" which is really the
only thing you can do... subscribe and unsubscribe from an event.

otherwise, check out some of the framework SDK stuff... HTH
 
J

Jeffrey Tan[MSFT]

Hi Trevor,

Do you still have any concern?
Please feel free to let me know.

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
 

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