Friday, May 7, 2021

C# Anonymous Method

Anonymous Method
  • What if a method is without name?
  • What components of the method will remain if the method is anonymous i.e. without any name?
Following facts can be said about anonymous method:
  1. Anonymous method is without name.
  2. Anonymous method can be parameter less or with parameters like any method.
  3. Anonymous method will have body and can have local variables inside this body. The body will be denoted by curly braces {} like any other methods.
  4. Anonymous method will have signature like any methods.
  5. Anonymous method will have declaration and definition together. 
  6. Anonymous method will have return type which will be of delegate type. This is unlike named methods. As anonymous method has delegate return type so that anonymous method must be assigned to a compatible delegate type instance.
  7. As delegate can be parameter of a method, we can pass anonymous method to such method.
        Syntaxdelegate(parameters){ // Local variables... //Codes... };

The Evolution of Delegates in C#

  1. In C# 1.0, you created an instance of a delegate by explicitly initializing it with a method that was defined elsewhere in the code. 
  2. C# 2.0 introduced the concept of anonymous methods as a way to write unnamed inline statement blocks that can be executed in a delegate invocation. 
  3. C# 3.0 introduced lambda expressions, which are similar in concept to anonymous methods but more expressive and concise. These two features are known collectively as anonymous functions. 
  4. In general, applications that target .NET Framework 3.5 or later should use lambda expressions.

EXAMPLE

class Test

{
    delegate void MyDelegate(string s);
    static void Message(string s)   { Console.WriteLine(s); }
    static void Main(string[] args)

    {
        // Original delegate syntax required
        // initialization with a named method.

        MyDelegate testDelA = new MyDelegate(Message);

        // C# 2.0: A delegate can be initialized with
        // inline code, called an "anonymous method." This
        // method takes a string as an input parameter.

        MyDelegate testDelB = delegate(string s) { Console.WriteLine(s); };

        // C# 3.0. A delegate can be initialized with
        // a lambda expression. The lambda also takes a string
        // as an input parameter (x). The type of x is inferred by the compiler.

        MyDelegate testDelC = (x) => { Console.WriteLine(x); };

        // Invoke the delegates.

        testDelA("Hello. My name is M and I write lines.");

        testDelB("That's nothing. I'm anonymous and ");

        testDelC("I'm a famous author.");

    }

}

No comments:

Post a Comment

Hot Topics