Thursday, March 7, 2013

C# Anonymous Method

In C# 2.0, a new language feature has been introduced called Anonymous Method, which are similar to delegates, but requires less code. Creating anonymous methods is essentially a way to pass a code block as a delegate parameter.Here , I will try to explain the Anonymous Method with some simple examples.
In my previous posts, I explained Partial Methods,Contextual Keyword, C# Static Methods and some other articles related to C#.

Anonymous Method

An anonymous method is a method with out name, just the body. It is created using the keyword delegate  and doesn't required name and return type. An anonymous method behaves like a regular method and allow us to write inline code.

 

Features of Anonymous Method

  • A variables, declared outside of the anonymous method can be accessed within anonymous methods. These variables are called outer or captured variable of anonymous method.
  • Use of jump statement like goto, break or continue inside anonymous method whose target is outside the anonymous method block, gives an error.
  • An anonymous method can not access the ref and out parameters of an outer scope.
  • Unsafe code can not be accessed within an anonymous method.

 

Syntax for Writing an Anonymous Method

Anonymous methods are declared with the creation of the delegate instance, with a delegate keyword. For example,

delegate void TestDelegate(string strMessage);
...
TestDelegate td = delegate(string str)
{
  Console.WriteLine(str);
};

The delegate could be called both with anonymous methods as well as named methods in the same way, i.e., by passing the method parameters to the delegate object.

 

Example-

using System;
namespace AnonymousMethod
{
    class Program
    {
        delegate void TestDelegate(string strMessage);
        public static void Print(string strmsg)
        {
            Console.WriteLine(strmsg);
        }
        static void Main(string[] args)
        {
            //create delegate instances using anonymous method
            TestDelegate td = delegate(string str)
            {
                Console.WriteLine(str);
            };
            //calling the delegate using the anonymous method
            td("Anonymous Method");
           
            //instantiating the delegate using the named methods
            td = new TestDelegate(Print);

            //calling the delegate using the named methods
            td("Named Method");

            Console.ReadKey();
        }
    }
}

When you run the above code, you will get the following results
Anonymous Method
Named Method

3 comments:

  1. I think it is worth noting that there are a few other ways of syntactically declaring an anonymous method such as Action/Func and lambda functions: The methods below could be used in your original post to show these:

    // create an Action which encapsulates a delegate
    Action action = str => Console.WriteLine(str);
    // calling the Action delegate operates in the same way as calling a named method but without having to define the method outside of the current scope
    td = new TestDelegate(action);
    td("Action Method");

    // create the method as a lambda function
    td = new TestDelegate(str => Console.WriteLine(str));
    // A lambda gives us a more declarative way to create an anonymous delegate but works in just the same way under the hood
    td("Lambda Function");

    ReplyDelete

^ Scroll to Top