C
C#2y ago
Vyrania

❔ Delegates and events

I'm trying to understand what these are, but I'm struggling a lot. I remember working with events when I was making a discord bot, but that was with discord ruby and discord py. Can someone help me understand this better? A simple analogy would be great since that's how I understand things best ><
10 Replies
Angius
Angius2y ago
Delegates are basically function pointers https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/delegates/ And events allow for easy pub-sub kind of communication https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/events/ Since you wanted analogies... Delegates are methods you can store in a variable Events are like subscribing to some thread on Discord, you get a notification when someone leaves a message
Vyrania
VyraniaOP2y ago
wait, you can store methods in blobwoah is news to me
Angius
Angius2y ago
Yep
MODiX
MODiX2y ago
Angius#1586
REPL Result: Success
Action<string> ungabunga = Console.WriteLine;

ungabunga("Hello world!");
Action<string> ungabunga = Console.WriteLine;

ungabunga("Hello world!");
Console Output
Hello world!
Hello world!
Compile: 601.120ms | Execution: 31.858ms | React with ❌ to remove this embed.
Angius
Angius2y ago
Alternatively,
MODiX
MODiX2y ago
Angius#1586
REPL Result: Success
delegate void unga(string stuff);

unga bunga = Console.WriteLine;

bunga("Hello world!");
delegate void unga(string stuff);

unga bunga = Console.WriteLine;

bunga("Hello world!");
Console Output
Hello world!
Hello world!
Compile: 666.180ms | Execution: 82.434ms | React with ❌ to remove this embed.
Angius
Angius2y ago
And let's not forget anonymous functions either
MODiX
MODiX2y ago
Angius#1586
REPL Result: Success
var sumIt = (int a, int b) => a + b;

sumIt(3, 7)
var sumIt = (int a, int b) => a + b;

sumIt(3, 7)
Result: int
10
10
Compile: 508.075ms | Execution: 59.199ms | React with ❌ to remove this embed.
Vyrania
VyraniaOP2y ago
Ahh okay
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server