Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences with delegate declaration in c# [duplicate]

Tags:

c#

delegates

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?

like image 568
Everts Avatar asked Jan 05 '13 20:01

Everts


People also ask

What are the differences between delegate and event?

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.

What is difference between delegate and method?

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.

What is the difference between delegate and func?

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.

What are the differences between events and delegates in C#?

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.


1 Answers

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.

like image 116
Brian Rasmussen Avatar answered Oct 19 '22 03:10

Brian Rasmussen