Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Anonymous or static or lambda methods??

Anonymous or static or lambda methods??

Scheduled Pinned Locked Moved C#
linqfunctionalquestion
8 Posts 4 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • S Offline
    S Offline
    Sea_Sharp
    wrote on last edited by
    #1

    It seems to me these three things are very quite similar. Can someone explain why you would use one over the others in given situations. Here I wrote a silly console app in which I was able to get all three types of methods to perform a simple math expression. Are there advantages / disadvantages to using one over another?

    class Program
    {
    delegate int GimmeTwoInts(int x, int y);

    static void Main(string\[\] args) 
    {
        ///Anonymous 
        GimmeTwoInts addThemUp = delegate(int x, int y) 
    

    { return x + y; };
    Console.WriteLine(addThemUp(5, 5));
    ///Output => 10

        ///Lambda
        GimmeTwoInts addAgain = (c, d) => { return c + d; };
        Console.WriteLine(addAgain(10, 10));
                  ///Output => 20
    
        ///Static
        Console.WriteLine(Program.AddingMachine(20, 20));
                  ///Output => 40
    
        Console.ReadLine();
    }
    
    public static int AddingMachine(int f, int g)
    {
         return f + g;
    }
    

    }

    M OriginalGriffO 2 Replies Last reply
    0
    • S Sea_Sharp

      It seems to me these three things are very quite similar. Can someone explain why you would use one over the others in given situations. Here I wrote a silly console app in which I was able to get all three types of methods to perform a simple math expression. Are there advantages / disadvantages to using one over another?

      class Program
      {
      delegate int GimmeTwoInts(int x, int y);

      static void Main(string\[\] args) 
      {
          ///Anonymous 
          GimmeTwoInts addThemUp = delegate(int x, int y) 
      

      { return x + y; };
      Console.WriteLine(addThemUp(5, 5));
      ///Output => 10

          ///Lambda
          GimmeTwoInts addAgain = (c, d) => { return c + d; };
          Console.WriteLine(addAgain(10, 10));
                    ///Output => 20
      
          ///Static
          Console.WriteLine(Program.AddingMachine(20, 20));
                    ///Output => 40
      
          Console.ReadLine();
      }
      
      public static int AddingMachine(int f, int g)
      {
           return f + g;
      }
      

      }

      M Offline
      M Offline
      Mycroft Holmes
      wrote on last edited by
      #2

      Anonymous has it's own obvious advantages and would be used for a specific requirement but I don't see any benefit either way on the other 2. I would always use the "static" method but then I don't normally consider linq by default.

      Never underestimate the power of human stupidity RAH

      1 Reply Last reply
      0
      • S Sea_Sharp

        It seems to me these three things are very quite similar. Can someone explain why you would use one over the others in given situations. Here I wrote a silly console app in which I was able to get all three types of methods to perform a simple math expression. Are there advantages / disadvantages to using one over another?

        class Program
        {
        delegate int GimmeTwoInts(int x, int y);

        static void Main(string\[\] args) 
        {
            ///Anonymous 
            GimmeTwoInts addThemUp = delegate(int x, int y) 
        

        { return x + y; };
        Console.WriteLine(addThemUp(5, 5));
        ///Output => 10

            ///Lambda
            GimmeTwoInts addAgain = (c, d) => { return c + d; };
            Console.WriteLine(addAgain(10, 10));
                      ///Output => 20
        
            ///Static
            Console.WriteLine(Program.AddingMachine(20, 20));
                      ///Output => 40
        
            Console.ReadLine();
        }
        
        public static int AddingMachine(int f, int g)
        {
             return f + g;
        }
        

        }

        OriginalGriffO Offline
        OriginalGriffO Offline
        OriginalGriff
        wrote on last edited by
        #3

        The three aren't "very quite similar" - the static method is a different animal altogether from the other two. Anonymous and Lambda methods cannot be static: they are always instance related. A static method is not instance related: you cannot use the this reference inside a static method explicitly or implicitly - which means you can't access non-static class properties, fields, or methods at all. So you can't do this:

        private int myInt = 666;
        public static void MyStaticMethod()
        {
        Console.WriteLine(myInt);
        }

        Because the compiler will complain that "An object reference is required for the non-static field, method, or property '... .myInt'" And there is no way to find the object reference because it is never, ever provided for a static method. If you remove the keyword static from your example, then the three calls become equivalent. But... you wouldn't normally do that! The Lambda you use for a very simple method that you are going to do in one place only, and it is frequently used for Linq to process all the elements in a collection - outside that context it's a bit overkill (why not just do the code inline?) Delegates are different: while you can use them the way you show, you would have to agree it's very "clumsy"! That's partly why Lambdas were introduced with Linq - to give a "cleaner" syntax to doing the same thing, and that's effectively what a Lambda is: an anonymous Delegate! But Delegates are move powerful that that: you can use the delegate repeatedly, or pass it through to a method. This allows you to write code which calls the delegate to "do something" without knowing exactly what the delegate is going to do! For example, you could set up a method to list out a log from a DB, and give it a delegate which does the actual output - then call the same method to output to the console, a textbox, a file,... without changing the actual method in any way!

        Those who fail to learn history are doomed to repeat it. --- George Santayana (December 16, 1863 – September 26, 1952) Those who fail to clear history are doomed to explain it. --- OriginalGriff (February 24, 1959 – ∞)

        "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
        "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

        Richard DeemingR S 2 Replies Last reply
        0
        • OriginalGriffO OriginalGriff

          The three aren't "very quite similar" - the static method is a different animal altogether from the other two. Anonymous and Lambda methods cannot be static: they are always instance related. A static method is not instance related: you cannot use the this reference inside a static method explicitly or implicitly - which means you can't access non-static class properties, fields, or methods at all. So you can't do this:

          private int myInt = 666;
          public static void MyStaticMethod()
          {
          Console.WriteLine(myInt);
          }

          Because the compiler will complain that "An object reference is required for the non-static field, method, or property '... .myInt'" And there is no way to find the object reference because it is never, ever provided for a static method. If you remove the keyword static from your example, then the three calls become equivalent. But... you wouldn't normally do that! The Lambda you use for a very simple method that you are going to do in one place only, and it is frequently used for Linq to process all the elements in a collection - outside that context it's a bit overkill (why not just do the code inline?) Delegates are different: while you can use them the way you show, you would have to agree it's very "clumsy"! That's partly why Lambdas were introduced with Linq - to give a "cleaner" syntax to doing the same thing, and that's effectively what a Lambda is: an anonymous Delegate! But Delegates are move powerful that that: you can use the delegate repeatedly, or pass it through to a method. This allows you to write code which calls the delegate to "do something" without knowing exactly what the delegate is going to do! For example, you could set up a method to list out a log from a DB, and give it a delegate which does the actual output - then call the same method to output to the console, a textbox, a file,... without changing the actual method in any way!

          Those who fail to learn history are doomed to repeat it. --- George Santayana (December 16, 1863 – September 26, 1952) Those who fail to clear history are doomed to explain it. --- OriginalGriff (February 24, 1959 – ∞)

          Richard DeemingR Offline
          Richard DeemingR Offline
          Richard Deeming
          wrote on last edited by
          #4

          OriginalGriff wrote:

          Anonymous and Lambda methods cannot be static: they are always instance related.

          Are you sure? As I understand it, there are three possibilities:

          • If the method captures local variables, it will be compiled as an instance method on a nested private class with fields to represent all of the captured variables;
          • Otherwise, if the method references instance fields, properties or methods of the current instance, it will be created as a private instance method;
          • Finally, if it only references static fields, properties or methods, or doesn't reference anything beyond its parameters, it will be created as a private static method;

          "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

          "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

          1 Reply Last reply
          0
          • OriginalGriffO OriginalGriff

            The three aren't "very quite similar" - the static method is a different animal altogether from the other two. Anonymous and Lambda methods cannot be static: they are always instance related. A static method is not instance related: you cannot use the this reference inside a static method explicitly or implicitly - which means you can't access non-static class properties, fields, or methods at all. So you can't do this:

            private int myInt = 666;
            public static void MyStaticMethod()
            {
            Console.WriteLine(myInt);
            }

            Because the compiler will complain that "An object reference is required for the non-static field, method, or property '... .myInt'" And there is no way to find the object reference because it is never, ever provided for a static method. If you remove the keyword static from your example, then the three calls become equivalent. But... you wouldn't normally do that! The Lambda you use for a very simple method that you are going to do in one place only, and it is frequently used for Linq to process all the elements in a collection - outside that context it's a bit overkill (why not just do the code inline?) Delegates are different: while you can use them the way you show, you would have to agree it's very "clumsy"! That's partly why Lambdas were introduced with Linq - to give a "cleaner" syntax to doing the same thing, and that's effectively what a Lambda is: an anonymous Delegate! But Delegates are move powerful that that: you can use the delegate repeatedly, or pass it through to a method. This allows you to write code which calls the delegate to "do something" without knowing exactly what the delegate is going to do! For example, you could set up a method to list out a log from a DB, and give it a delegate which does the actual output - then call the same method to output to the console, a textbox, a file,... without changing the actual method in any way!

            Those who fail to learn history are doomed to repeat it. --- George Santayana (December 16, 1863 – September 26, 1952) Those who fail to clear history are doomed to explain it. --- OriginalGriff (February 24, 1959 – ∞)

            S Offline
            S Offline
            Sea_Sharp
            wrote on last edited by
            #5

            Very interesting. Just to make sure I pull the nugget of info I was mining for. In regards to how anonymous/lambda compare to named functions in general is the following true? It seems to me the delegate is really kind of like a contract in which you provide parameters types and a potential return type without any method body. Then you can subsequently use that delegate(contract) in combination with an anonymous/lambda expression to perform the given instructions. If I understand this correctly then, I still fail to see the benefit of the delegates and the anonymous/lambda functions. Could you not just create named functions for all the processing you will complete? If you still have to provide instructions to every anonymous/lambda expression call, then how are they even advantageous? I can't see how it would either reduce the amount of code, improve readability, or make it any easier to call particular functionality.

            OriginalGriffO 1 Reply Last reply
            0
            • S Sea_Sharp

              Very interesting. Just to make sure I pull the nugget of info I was mining for. In regards to how anonymous/lambda compare to named functions in general is the following true? It seems to me the delegate is really kind of like a contract in which you provide parameters types and a potential return type without any method body. Then you can subsequently use that delegate(contract) in combination with an anonymous/lambda expression to perform the given instructions. If I understand this correctly then, I still fail to see the benefit of the delegates and the anonymous/lambda functions. Could you not just create named functions for all the processing you will complete? If you still have to provide instructions to every anonymous/lambda expression call, then how are they even advantageous? I can't see how it would either reduce the amount of code, improve readability, or make it any easier to call particular functionality.

              OriginalGriffO Offline
              OriginalGriffO Offline
              OriginalGriff
              wrote on last edited by
              #6

              A delegate doesn't have to be a lambda or anonymous function - it can be a named function as well: in fact it can be a list of functions, provided the method signature matches the delegate template and all of them will be called. Try it:

              public delegate int MyDelegate(string x);
              public MyDelegate theDelegate;

              theDelegate += (x) => {Console.WriteLine("Lambda {0}", x); return x.Length; };
              theDelegate += delegate(string x) { Console.WriteLine("Anonymous {0}", x); return x.Length; };
              theDelegate += Named;
              theDelegate("hello");
              }
              

              private int Named(string x)
              {
              Console.WriteLine("Named {0}", x);
              return x.Length;
              }

              And you will get:

              Lambda hello
              Anonymous hello
              Named hello

              So you can use delegates to "chain" methods together - and in fact you use this all the time: delegates are what makes Events work! So yes, in a way a delegate is a "contract" in that it specifies the method signature which it can accept - but don't really think of it like that, because it's main task is as a function pointer: it allows you to write code that doesn't need to know exactly what it is calling, just that "it takes these parameters and it returns such-and-such". So it would be (relatively) easy to write code which used delegates to work (seamlessly) with SQL Server, MySql and CSV files - without the code needing to know what kind of storage medium is behind it: it just calls the "write this to this table" and "get this from that table" delegates and the outside world sorts out the actual code to do that. Without delegates, you couldn't do that in C# - you have to write code which explicitly checked:

              if (usingMSSQL) ReadFromMsSQL(table, columnlist);
              else if (usingMySQL) ReadFromMySQL(table, columnlist);
              else if (usingCSV) ReadFromCSV(table, columnlist);
              else Throw new IDontKnowWhatToDoException("HELP!");

              ANd write similar code for every other method you need: INSERT, DELETE, UPDATE, and so forth. Then to add another (Excel perhaps) you have to change the code to support it - and risk missing one, or messing up, or otherwise getting it wrong. OK, that's an advanced form, that you probably won't need to use for years, if ever - but Events are handled via exactly the same mechanism - and it just isn't possible to "add methods" to .NET code to include your event handler methods because (most of us) didn't even have access to the .NET source until fa

              "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
              "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

              S 1 Reply Last reply
              0
              • OriginalGriffO OriginalGriff

                A delegate doesn't have to be a lambda or anonymous function - it can be a named function as well: in fact it can be a list of functions, provided the method signature matches the delegate template and all of them will be called. Try it:

                public delegate int MyDelegate(string x);
                public MyDelegate theDelegate;

                theDelegate += (x) => {Console.WriteLine("Lambda {0}", x); return x.Length; };
                theDelegate += delegate(string x) { Console.WriteLine("Anonymous {0}", x); return x.Length; };
                theDelegate += Named;
                theDelegate("hello");
                }
                

                private int Named(string x)
                {
                Console.WriteLine("Named {0}", x);
                return x.Length;
                }

                And you will get:

                Lambda hello
                Anonymous hello
                Named hello

                So you can use delegates to "chain" methods together - and in fact you use this all the time: delegates are what makes Events work! So yes, in a way a delegate is a "contract" in that it specifies the method signature which it can accept - but don't really think of it like that, because it's main task is as a function pointer: it allows you to write code that doesn't need to know exactly what it is calling, just that "it takes these parameters and it returns such-and-such". So it would be (relatively) easy to write code which used delegates to work (seamlessly) with SQL Server, MySql and CSV files - without the code needing to know what kind of storage medium is behind it: it just calls the "write this to this table" and "get this from that table" delegates and the outside world sorts out the actual code to do that. Without delegates, you couldn't do that in C# - you have to write code which explicitly checked:

                if (usingMSSQL) ReadFromMsSQL(table, columnlist);
                else if (usingMySQL) ReadFromMySQL(table, columnlist);
                else if (usingCSV) ReadFromCSV(table, columnlist);
                else Throw new IDontKnowWhatToDoException("HELP!");

                ANd write similar code for every other method you need: INSERT, DELETE, UPDATE, and so forth. Then to add another (Excel perhaps) you have to change the code to support it - and risk missing one, or messing up, or otherwise getting it wrong. OK, that's an advanced form, that you probably won't need to use for years, if ever - but Events are handled via exactly the same mechanism - and it just isn't possible to "add methods" to .NET code to include your event handler methods because (most of us) didn't even have access to the .NET source until fa

                S Offline
                S Offline
                Sea_Sharp
                wrote on last edited by
                #7

                Wow thank you so very much! That was enlightening. Totally had that epiphany moment looking at your examples. K+

                OriginalGriffO 1 Reply Last reply
                0
                • S Sea_Sharp

                  Wow thank you so very much! That was enlightening. Totally had that epiphany moment looking at your examples. K+

                  OriginalGriffO Offline
                  OriginalGriffO Offline
                  OriginalGriff
                  wrote on last edited by
                  #8

                  You're welcome!

                  Those who fail to learn history are doomed to repeat it. --- George Santayana (December 16, 1863 – September 26, 1952) Those who fail to clear history are doomed to explain it. --- OriginalGriff (February 24, 1959 – ∞)

                  "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
                  "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

                  1 Reply Last reply
                  0
                  Reply
                  • Reply as topic
                  Log in to reply
                  • Oldest to Newest
                  • Newest to Oldest
                  • Most Votes


                  • Login

                  • Don't have an account? Register

                  • Login or register to search.
                  • First post
                    Last post
                  0
                  • Categories
                  • Recent
                  • Tags
                  • Popular
                  • World
                  • Users
                  • Groups