Delegate functions have to be static?

  • Thread starter Thread starter Bryan Bullard
  • Start date Start date
B

Bryan Bullard

Hi,

I've been looking at examples of delegates in C#. All the examples show
delegates are references to static methods. Can delegates be used with
instance methods?

Thanks in advance,
Bryan
 
Bryan,

Yes, absolutely they can. All you have to do is when creating the
delegate, pass the variable name with a reference, then the method name,
like so:

// Say that MyObject has a method that has the signature of the EventHandler
delegate
// called SomeMethod. You can do:
MyObject pobjObject = new MyObject();

// Create the event handler.
EventHandler pobjHandler = new EventHanlder(pobjObject.SomeMethod);

Hope this helps.
 
Nicholas Paldino said:
Bryan,

Yes, absolutely they can. All you have to do is when creating the
delegate, pass the variable name with a reference, then the method name,
like so:

// Say that MyObject has a method that has the signature of the EventHandler
delegate
// called SomeMethod. You can do:
MyObject pobjObject = new MyObject();

// Create the event handler.
EventHandler pobjHandler = new EventHanlder(pobjObject.SomeMethod);

Hope this helps.

....

Very helpful, thanks.
 
Back
Top