C
C#4w ago

When should one use a custom delegate instead of Func/Action/Predicate?

Title.
80 Replies
Evyr
Evyr4w ago
It's a good way to make sure people aren't doing silly things. If you use Func/Action then you can pass anything with the same parameters and return type, even though it could do something wildly different. Restricting arguments to a specific type of delegate means whoever's using that function has a sanity check to make sure they're not misusing it Func/Action/Delegate are also part of the base class library whereas delegate is just a part of the language, though I can't think of many situations where that'd matter Oh when, not why, sorry Though the same logic applies
Angius
Angius4w ago
Func and Action are very simple. Those are the types I expect as input, this is (or isn't) the type I will give as an output. Delegates can be generic, can have named parameters, can have ref parameters, pretty sure out as well
Sossenbinder
Sossenbinder4w ago
Custom delegates also allow optional arguments, and I sometimes like to use them because naming them is often helpful for readability So instead of an Action<T> I could have a "XXXCallback" in the codebase
fæ
OP4w ago
What about using the Delegate type directly?
Angius
Angius4w ago
Never used it
fæ
OP4w ago
like this
No description
Angius
Angius4w ago
Makes no sense to me over using an Action<string> It smells of using an object or dynamic that's basically "whatever lmao"
Evyr
Evyr4w ago
Delegate is the base class for Func and Action iirc
fæ
OP4w ago
i thought they were defined using the delegate keyword i understand that but isnt that the same as Action<T>? they're both generic
Evyr
Evyr4w ago
Func and Action are delegate types in the base class language and are delegates, the delegate keyword defines a new delegate
Angius
Angius4w ago
Action<int> will take only a void method that takes one single int parameter Delegate will take anything void Foo(int x)? Sure. string Bar(int a, int b, Person c)? Why not (int a, string b, Func<int, Person> c) Baz(IQueryable<Dictionary<string, int>> quaz)? Sure, fuck me up
fæ
OP4w ago
well handleEvent("click", callbackgoeshere) what if i want literally any callback I dont really wanna impose a restriction
Angius
Angius4w ago
How do you reason about it? When you invoke it, what do you give it as parameters?
fæ
OP4w ago
i want to let the user handle the event hwoever they want? if the click event gets fired they can chose any behavior they want
Angius
Angius4w ago
What do you expect in return?
fæ
OP4w ago
they could launch a new process. they could print to the console. they could close the current process. idk
Angius
Angius4w ago
Right, so, the user passes a delegate with this signature:
(int a, string b, Func<int, Person> c) Baz(IQueryable<Dictionary<string, int>> quaz)
(int a, string b, Func<int, Person> c) Baz(IQueryable<Dictionary<string, int>> quaz)
how do you invoke it?
fæ
OP4w ago
delegate.Method.Invoke()?
fæ
OP4w ago
No description
Angius
Angius4w ago
And what parameters you give it, if it can be anything?
fæ
OP4w ago
well Invoke takes object[] so anything... not sure how to answer that
Angius
Angius4w ago
Yeah, and what will be inside of it? Exactly The user can still do anything they want inside of an Action No parameters, void return type It still captures outside variables, for example
fæ
OP4w ago
sure, i understand that
fæ
OP4w ago
i see action has some syntactic sugar to let you invoke it as if it was a method
No description
Angius
Angius4w ago
Yep
surf68
surf684w ago
plus, Delegate doesn't actually give you a free-for-all, you just get a runtime error if the arguments don't match those expected by the actual argument provided so you're essentially breaking out of the type system for zero gain in much the same way as passing objects around
fæ
OP4w ago
are you two acquainted with object.addEventHandler in JS?
surf68
surf684w ago
yes
Angius
Angius4w ago
What it expects is a function that takes an Event and returns nothing So an Action<Event> in C# terms
fæ
OP4w ago
the way this works is that object.addEventHandler(eventName : string, callback : Function) will add the callback instead of overwriting. Meaning that you can do that multiple times for multiple functions and trigger all of them when the event fires Is this what multicasting is in C#?
Angius
Angius4w ago
What you're looking for is events, then Or just a list of Actions you can keep adding to and execute them in a loop
fæ
OP4w ago
I dont quite get this then
No description
surf68
surf684w ago
multicast delegates aren't quite the same as event handlers, no
Angius
Angius4w ago
Uh, I guess another weirdness of Delegates...?
Evyr
Evyr4w ago
You're casting multiple methods to the delegate type, then when you invoke that delegate it sequentially invokes each method assigned to it
Angius
Angius4w ago
I won't be of much help here, I literally never seen bare Delegate used anywhere
surf68
surf684w ago
multicast delegates are essentially like adding multiple delegates together so that you can refer to the invocation of both (in the case of two) in one place
Evyr
Evyr4w ago
you can do events that way, but C# has a convention with events using the event keyword Because all delegates have invocation lists, not just events the convention is you define your delegate type for the event, say
delegate void MyEventDelegate(object sender, MyEventArgs e);
event MyEventDelegate MyEvent;
delegate void MyEventDelegate(object sender, MyEventArgs e);
event MyEventDelegate MyEvent;
then you can subscribe to that event
surf68
surf684w ago
you can have a multicast delegate without having anything to do with events, whereas addEventListener is specific to events on an instance
fæ
OP4w ago
nah this is also applicable to Actions
Evyr
Evyr4w ago
but you can just as well have MyEventDelegate MyEvent on its own and subscribe to it, you just won't have a couple of extra protections, bells and whistles that come with events specifically
fæ
OP4w ago
from what i understand i can do
Action a = method1 + method2 + method3;
Action a = method1 + method2 + method3;
and when the delegate gets invoked as a callback it will execute the three methods in order, correct?
Evyr
Evyr4w ago
When you invoke any delegate type, whether it be Func, Action, Delegate, Event, etc it just invokes every method added to its invocation list sequentially, and if that delegate type has a return type, it returns the result of the last delegate in its invocation list Correct, yeah
fæ
OP4w ago
got it
Evyr
Evyr4w ago
if that was Func a = func1 + func2 + func3; with a return type, it'll return the result of func3 only, not a sum of them, but 99% of the time that doesn't matter
fæ
OP4w ago
why are people saying that events should be avoided and only delegates should be used?
fæ
OP4w ago
Nick Chapsas
YouTube
Are events in C# even relevant anymore?
Check out my courses: https://dometrain.com Become a Patreon and get source code access: https://www.patreon.com/nickchapsas Hello everybody I'm Nick and in this video I will explain why I think that events as a feature in C# is obsolete and how we can implement the same event-like mechanism in a modern and elegant way. Timestamps Intro - 0:00...
Angius
Angius4w ago
For content
fæ
OP4w ago
ic
surf68
surf684w ago
honestly, beats me. you can use delegates in a similar way to events but there are distinct differences.
fæ
OP4w ago
i was wondering if there was any merit to this
surf68
surf684w ago
to me that video is pure bunk. someone linked it earlier as reasoning behind abandoning events and the conclusion of that video is to use MediatR. it's wild.
fæ
OP4w ago
alright, so i'm a typescript/angular dev right. you would use C# events/delegates if you wanted to implement the subscriber/observer pattern?
surf68
surf684w ago
not that there's anything wrong with MediatR but you certainly wouldn't use it in a lot of cases you'd use events.
fæ
OP4w ago
if i recall its called something else in the C# world, publisher/subscriber i think
surf68
surf684w ago
if you're used to JS events, they're pretty much a direct analogue
fæ
OP4w ago
i see do people use libraries for this kinda stuff?
surf68
surf684w ago
there's just some syntactic sugar around adding/removing event handlers
fæ
OP4w ago
is rx a thing in the C# ecosystem
surf68
surf684w ago
i.e. x.addEventListener("click", () => { ... }) becomes x.Click += () => {...}
fæ
OP4w ago
that is oddly wpf'esque I remember trying to make a WPF desktop application when i was younger, i remember doing that for some buttons. little did i know i was using delegates this whole time
surf68
surf684w ago
well they're events but yes, events are delegates with some additional rules
fæ
OP4w ago
yeah i hate the world
No description
surf68
surf684w ago
what's there to hate?
fæ
OP4w ago
but hold on i can use the delegate keyword to create anonymous methods? why has no one told me this
Action<string> a = delegate (string s) { Console.WriteLine(s); };
Action<string> a = delegate (string s) { Console.WriteLine(s); };
vs
Action<string> a = (string s) => { Console.WriteLine(s); };
Action<string> a = (string s) => { Console.WriteLine(s); };
are both of these "anonymous methods"?
Evyr
Evyr4w ago
yeah they're both anonymous functions you could also do Action<string> = Console.WriteLine in this case
fæ
OP4w ago
I think you can only do that if the method group has only one overload in this case it might be confused as to which WriteLine you're talking about unless it infers it from the <string>?
surf68
surf684w ago
they're both anonymous methods
fæ
OP4w ago
can confirm, it does infer it it's only an issue if you do
var write = Console.Write; // ERROR: Multiple overloads, can't choose
var write = Console.Write; // ERROR: Multiple overloads, can't choose
Uchiha Wick
Uchiha Wick4w ago
someone could help me with a save botton?
surf68
surf684w ago
syntax in the second came about in a later version of C#
fæ
OP4w ago
they are called lambdas?
surf68
surf684w ago
lambda expressions, yeah
fæ
OP4w ago
is it necessary to instanciate a delegate type? what's the difference between
myDelegate md = myMethod
myDelegate md = myMethod
and
myDelegate md = new myDelegate(md);
myDelegate md = new myDelegate(md);
surf68
surf684w ago
no difference
fæ
OP4w ago
thank you
surf68
surf684w ago
anyhow I'm off, good luck in your delegate travels
fæ
OP4w ago
<3 take care
Evyr
Evyr4w ago
if you're using += then yes, but if you're assigning to md then no
Joschi
Joschi4w ago
Multicast delegates is how events are implement in C# as far as I know. Delegates are not that often used, but they are valuable if you go deeper into the functional style of C#. https://www.youtube.com/watch?v=2TXvwUgaMHs&t=1s
Zoran Horvat
YouTube
Master the Design of Functional Behavior in C#
How do we implement functions in a class-based programming language, such as C#? The latest C# programming language specification offers a rich syntax that supports functional programming in this versatile language. Functional design is known for its simplicity and the short code it produces compared to other design techniques we apply. It is ba...
Want results from more Discord servers?
Add your server