C#: Anonymous method vs Named method

后端 未结 5 1428
渐次进展
渐次进展 2020-12-10 05:19

I\'m new to SO and programming and learning day by day with bits and pieces of tech (C#) jargons.

After Googling for a while, below is what I\'ve researched about

5条回答
  •  囚心锁ツ
    2020-12-10 05:36

    Explanation by Analogy

    Normally when we tell stories we refer to people by name:

    "Freddie"

    "Who's Freddie?"

    "You know, Freddie, Freddie from Sales - the male guy with the red hair, who burned the building down...?"

    In reality nobody cares who the person is, department he works etc. it's not like we'll refer to him every again. We want to be able to say: "Some guy burned down our building". All the other stuff (hair color, name etc.) is irrelevant and/or can be inferred.

    What does this have to do with c#?

    Typically in c# you would have to define a method if you want to use it: you must tell the compiler (typically):

    • what it is called,
    • and what goes into it (parameters + their types),
    • as well as what should come out (return type),
    • and whether it is something you can do in the privacy of your home or whether you can do it in public. (scope)

    When you do that with methods, you are basically using named methods. But writing them out: that's a lot of effort. Especially if all of that can be inferred and you're never going to use it again.

    That's basically where anonymous methods come in. It's like a disposable method - something quick and dirty - it reduces the amount you have to type in. That's basically the purpose of them.

提交回复
热议问题