Poll of the Day > What's the point of using a delegate

Topic List
Page List: 1
Yellow
12/18/20 11:00:12 PM
#1:


In C# or otherwise, over

EventHandler
Action
Func

Maybe it's on me for not learning this effectively, but they just seem like more complicated versions of the former classes. The best explanation I can get is that it's used to share a method with another object... but you can just pass it directly using Action or Func?

---
why am I even here
... Copied to Clipboard!
LuciferSage
12/19/20 1:44:01 AM
#2:


It's better than a GOTO...

---
... Copied to Clipboard!
Sahuagin
12/19/20 1:23:29 PM
#3:


Depends what you mean.

Before lambda syntax, there were "anonymous functions", which looked like this: delegate (int x) { return x; }

which is basically equivalent to: x => x or (int x) => x

but there are also named function signatures. so instead of Func<Action, Action<string>, Action> you can have a line like this:

delegate Action MyFancySignature(Action action, Action<string> otherAction);

and then define a reference variable:

MyFancySignature something = GetSomething();

but generally it's suggested to use Func and Action instead.

(note also that Func and Action are themselves defined this way IIRC:
public delegate T Func<T>();
public delegate TOut Func<TIn, TOut>(TIn in);
public delegate void Action();
public delegate void Action<T>(T first);
// etc... (slightly more complicated with covariance/contravariance)

one exception is when using out parameters, which can't be defined using Func and Action.

For example, to capture the signature of TryParse methods, you need something like this:

public delegate bool TryParser<T>(string str, out T value);

And then, for your question, it depends too what you're calling a "delegate". A "delegate" really is basically sort of a "managed function pointer". it's an invisible object that manages a reference to a function/method.

When you say MyFancySignature something = this.SomeMethod; it implicitly means something more like MyFancySignature something = new MyFancySignature(this.SomeMethod); creating a new object (a delegate) that behind the scenes manages (I presume) a pointer to a method. this is the same kind of object that is made when you write an anonymous function, so I guess that's why they used the keyword delegate for the original anonymous functions.

---
... Copied to Clipboard!
Topic List
Page List: 1