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
=> 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
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 intsok i got it
👍
so delegates are a way to store methods ?
yes, correct
you can conceptually think of them as a
List<method>
method
is a type ?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 boolok makes more sens
thanks a lot
no prob. have fun using lambdas
they are very powerful