Search This Blog

Wednesday 23 July 2014

Delegates and Events in C#

Delegates and Events in C#

Delegates and Events Both are related.

Dalegete is a function pointer which can able to store the address of any function with same prototype.

Event is a function handler which can handles or run the functions in same prototype of its delegate.

For handling events delegate is used.


For example you have class where you have a public instance of a delegate and and a event of the same delegate type

public delegate void TestDel(Object seder,string args);
public class DelegateEventTest
{
public TestDel aDelegate;

public event TestDel aEvent;
}

Now from your main method which is in a separate class you can raise delegate but you cannot raise the event . Evet can only be raised within the same class(here class DelegateEventTest).


class Program
{
static void Main(string[] args)
{
DelegateEventTest test = new DelegateEventTest();
test.aDelegate = new TestDel(MethodtoTestDelegate);
/* This line will never compile*/
// test.aEvent = new TestDel(MethodtoTestDelegate);
}

static void MethodtoTestDelegate(Object o, string a)
{
}
}

No comments:

Post a Comment