Sunday, August 17, 2014

Understanding anonymous methods in delegates

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApps
{
class UnderstandingAnonymousMethod
{
public delegate int ArithmeticOperator(int a, int b); // Anonymous delegate with arguments

public delegate void PrintDelegate(); // Anonymous delegate without arguments

public delegate void NormalDelegateExample();

public delegate void GroupConversionDelegate();


public static void Main()
{


ArithmeticOperator addop = delegate(int n1, int n2)
{
  return n1 + n2;
};
Console.WriteLine(addop(10, 20));  // Prints 30




PrintDelegate pt = delegate
{
   Console.WriteLine("Anonymous delegate executed");
};
pt();  // Prints "Anonymous delegate executed"




NormalDelegateExample nm = new NormalDelegateExample(Print);
nm();      // Prints "Normal delegate example"

GroupConversionDelegate gd = Print2;
gd();       // Prints "Group Conversion delegate example"

}



        public static void Print()
        {
            Console.WriteLine("Normal delegate example");
        }
        public static void Print2()
        {
            Console.WriteLine("Group Conversion delegate example");
        }
    }
}


 delegate is a reference type variable that holds the reference to a method

No comments:

Post a Comment