Difference between delegates and events?
Difference between delegates and events?
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Sujeet SumanPosted Oct 12, 2015, 2:55 AM
Priyaranjan K SPosted Oct 12, 2015, 12:59 AM
Nilesh JadavPosted Oct 12, 2015, 12:55 AM
Delegate:
A delegate in C# is similar to a function pointer in C. A delegate object holds the reference of one or more methods. Delegate creation is the four steps process.A delegate object doesn't care about the class in which the function exists. There is only one restriction that the delegate signature and the function signature should be same otherwise delegate object can’t hold the reference of the method which doesn't have the same signature. Signature means return type and parameters.
Example
public class Math
{
public static int Add(int i, int j)
{
return i + j;
}
}
class DelegateAndEvent
{
//Delegate Declaration
public delegate int MathFunctions(int i, int j);
static void Main()
{
//Delegate object creation.
MathFunctions MathFun = null;
//Point the reference to the method.
MathFun += Math.Add;
// Invoke delegate.
int value = MathFun.Invoke(10, 20);
Console.WriteLine(value.ToString());
Console.ReadLine();
}
}
Events:
Event is a mechanism by which a class can send notification to its client. For example, you have an application to perform certain operation, if an operation is failed then the application send the notification to log file, printer, fax, email etc.
Events are declared using delegates. Without delegate, we can not create Events.
Read this Full Article that describes much more about Delegates and Events with enhanced example :
http://einterviewquestions.blogspot.in/2012/12/difference-between-delegate-and-events.html
Ravi PatelPosted Oct 12, 2015, 12:50 AM
Basically, events provide for a tightly coupled publish subscribe paradigm, while delegates provide for a much more loosely coupled design.
for more details
Rajeesh MenothPosted Oct 11, 2015, 1:30 PM