Search code examples
c#anonymous-functionanonymous-methods

C#: Anonymous method vs Named method


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 methods

  1. A Method is a block of statements, which serves for code reusability & it also supports overloading with different SIGNATURE....for ex: drawShape(2pts), drawShape(3pts) etc...

  2. An Anonymous method is one with block of statements, but no name....(as its premature to ask, in wt situation we come across anonymous method...any articles, samples ...)

  3. Named method: Here's a link but at the end i didn't get what Named Method actually is...

Can anyone explain what a "Named" method is, and where do we use anonymous method?


Solution

  • A named method is a method you can call by its name (e.g. it is a function that has a name). For example, you have defined a function to add two numbers:

    int f(int x, int y)
    {
        return x+y;
    }
    

    You would call this method by its name like so: f(1, 2);.

    Anonymous method is a method that is passed as an argument to a function without the need for its name. These methods can be constructed at runtime or evaluated from a lambda expression at compile time.

    These methods are often used in LINQ queries, for example:

    int maxSmallerThan10 = array.Where(x => x < 10).Max();
    

    The expression x => x < 10 is called a lambda expression and its result is an anonymous function that will be run by the method Where.

    If you are a beginner, I would suggest you first read about more basic stuff. Check out the following links: