Search This Blog

Tuesday, January 24, 2012

what is delegates and why is it require???

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

namespace Delegates1//Used to pass method as argument
{

    public delegate string FirstDelegate(int x);

    class Program
    {
        static void Main(string[] args)
        {
            FirstDelegate d1 = new FirstDelegate(DelegateTest.StaticMethod);

            DelegateTest instance = new DelegateTest();
            instance.name = "My instance";
            FirstDelegate d2 = new FirstDelegate(instance.InstanceMethod);

            Console.WriteLine(d1(10)); // delegates d1 Writes out "Static method: 10"
            Console.WriteLine(d2(5));  // delegates d2 Writes out "My instance: 5"
            Console.ReadLine();
      
        }
    }
    class DelegateTest
    {
      public string name;

        public static string StaticMethod(int i)// It 's called by using class name
        {
            return string.Format("Static method: {0}", i);
        }

       public string InstanceMethod(int i)// it's called by using object of the class
        {
            return string.Format("{0}: {1}", name, i);
        }
    }
}

No comments:

Post a Comment