Possible Duplicate:
Why use “new DelegateType(Delegate)”?
What is the difference between new Thread(void Target()) and new Thread(new ThreadStart(void Target()))?
So I have been through a little bit of delegate and got the whole idea somehow. Now, I see everywhere exemple like this:
public delegate void Deleg();
Deleg deleg = new Deleg(FunctionName);
deleg();
I would think this creates an delegate object with the function to point at being passed as parameter to the constructor.
Now, I can also do like this:
public delegate void Deleg();
public Deleg deleg;
deleg = FunctionName;
deleg();
This one seems to only create a reference and the address of the function is passed. This works just the same and has all the delegate functionalities.
But now, regardless of the fact I have one more line in the second exemple, do I actually lose or gain something out of the second since the first one is more popular on tutorials?
Events Have Private Invocation Events are typically public class members. By comparison, delegates are often passed as parameters and stored as private class members, if they are stored at all.
A delegate is a method with a parameter and a return type. A delegate is a type that safely encapsulates a method. Delegates are object-oriented, type safe, and secure.
Func is a generic delegate included in the System namespace. It has zero or more input parameters and one out parameter. The last parameter is considered as an out parameter. This delegate can point to a method that takes up to 16 Parameters and returns a value.
Key Differences Between Delegates and Events in C# Delegate is an object used as a function pointer to hold the reference of a method. On the other hand, events provide an abstraction to delegates. A keyword required to declare a delegate is a delegate whereas, a keyword required to declare an event is event.
The gain is a little less typing. The compiler is smarter now than it was initially, so it can do the method group conversion implicitly which is why you don't have to do new Deleg(FunctionName)
anymore.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With