C
C#2mo ago
Frite

Lambda, delegates, events. Help !

So i wanted to learn events, and then i discovered delegates, and =>. I can't understand what it means and how to read it. help !
9 Replies
Becquerel
Becquerel2mo ago
=> is a shorthand for writing a method. the things before the => are the parameters/arguments, the stuff after the => is the code of the method 'int x => x * 2' is equivalent to 'int MultiplyByTwo(int x) { return x * 2; }' when you use lamba expressions (the 'proper' name for =>), you can often leave out the type of the parameters because the compiler can infer them. but you can always think of them as just being methods
var myList = new List<int> { 4, 5, 6 };
var filtered = myList.Where(number => number > 4);
var myList = new List<int> { 4, 5, 6 };
var filtered = myList.Where(number => number > 4);
this example passes an unnamed method to .Where with one parameter, called 'number', which is inferred to be an int because the list it's operating on is a list of ints
Frite
Frite2mo ago
ok i got it
Becquerel
Becquerel2mo ago
👍
Frite
Frite2mo ago
so delegates are a way to store methods ?
Becquerel
Becquerel2mo ago
yes, correct you can conceptually think of them as a List<method>
Frite
Frite2mo ago
method is a type ?
Becquerel
Becquerel2mo ago
and events are really just boilerplate for doing a foreach over that list and invoking all the methods you've stored in it no, i just made it up as an example c# is a strongly-typed language, so it doesn't let you just say 'i want to store all kinds of methods in this list'. instead you have to say 'i want to store methods with this specific return type, these number of arguments, and these types of arguments' 'delegate bool MyCoolDelegate(int x, int y);' represents all methods that take in two ints and return a bool
Frite
Frite2mo ago
ok makes more sens thanks a lot
Becquerel
Becquerel2mo ago
no prob. have fun using lambdas they are very powerful
Want results from more Discord servers?
Add your server