I'm trying to understand Delegates in C#. I'm not too deep down the rabbit hole yet; as far as I know they are just pointers. I made the mistake of trying to apply JavaScript logic to C# when trying to understand them originally (everything is let or const) however soon realized there was no way to assign methods. So I understand why we need Delegates, my question is:
Why do we declare them?
Instead of:
public delegate void Pointer(String text);
Pointer p = SomeMethod;
Why not just do:
var p = SomeMethod;
???
I'm sure there must be some advanced things I don't know yet but I just can't see why you would ever need to declare them the first way???
CodePudding user response:
Most of the time, I find that Action and Func suffice. One reason you might want to declare them is to pass them back into an event handler. For instance,
public delegate void MyEventHandler(object sender, MyEventArgs e);
And then you would follow that up with
public event MyEventHandler OnEvent;
This would let you subscribe to that event, presumably with custom arguments in MyEventArgs. In this case, you couldn't rely on var, though you could use Action to achieve a similar result without declaring the delegate prototype:
public event Action<object, MyEventArgs> OnEvent;
Why would you ever declare the delegate? For me, it mostly comes down to consistency. Declaring the delegate gives you one place where you can change your code if the signature ever changes, which also, in my opinion, makes your code more readable.
CodePudding user response:
Delegate types are commonly needed if you want to give the caller of a function the possability to calucalte something while the execution of the method (e.g. List<T>.ForEach
uses a delegate for calling a user defined function for each element).
A delegate type is defined the following:
<access modifier> deleage <function header>
Using this delegate assures the compiler, that the function takes the right parameters and returns a value of the right type. Of course this could be checked at runtime but this isn't the approach of C#. This is in contrast to dynamic typed languages (JavaScript, Python, ...), which might have the possability to just check at runtime whether the function matchs the requirements.
So you are right, it is theoretically not necessery but C#, Java and other static typed languages just require a definition of the function somewhere.
C# is static typed. So every object must have a known datatype. The var keyword just makes the compiler decide the datatype instead of the programmer.
But as it is in your example, you don't have to write a custom delegate for every thing, there are some standart delegates like Action
and Function
. If your function matchs one of those predefined interfaces you can assign them using the type explicitly (writing the datatype before the variable name) or implicitly just as you did with the var
keyword.