C# language feature:

  • Anonymous methods

applies to

  • delegates, function declarations

benefit

  • Allows defining delegates without boilerplate naming code.

how to use

  • 1) Define delegate.
  • 2) Declare delegate variable and assign to a delegate function with matching signature of defined delegate followed by with function/delegate body.

see also

  • Delegate inference, Method group conversions

example:

    delegate void My_Delegate_Definition(int x); // 1) define delegate
    class Anonymous_Method_Example {
        // 2) declare delegate variable and assign to a matching `delegate`signature followed by function/delegate body
        public My_Delegate_Definition delegate_variable = delegate(int k) { System.Console.WriteLine(k); }; //

        // Example without anonymous methods (both statements below would be needed)
        static void My_Function(int k) { System.Console.WriteLine(k); }  // define a named function with matching signature and function body
        My_Delegate_Definition bdelegate = new My_Delegate_Definition(Anonymous_Method_Example.My_Function);  // declare and assign function by name

    }

    // bonus example of generic delegate using anonymous method
    delegate void Generic_Delegate_Definition<T>(T x);
    class Use_of_Generic_Delegate_Definition
    {
        public Generic_Delegate_Definition<string> myfunction = delegate(string mystr) { System.Console.WriteLine(mystr); };
    }