AdBrite

Your Ad Here

Tuesday, December 14, 2010

C# Delegate

        // This "DoMath" delegate can point to ANY method that:
        //   - Returns an int
        //   - Accepts two ints as parameters
        public delegate int DoMath(int x, int y);

      
        private void button1_Click(object sender, EventArgs e)
        {
            int result;

            DoMath a = new DoMath(Add);
            result = a(3, 4);
            MessageBox.Show(Convert.ToString(result));

            UseDelegate(a);
        }


        public void UseDelegate(DoMath x)
        {
            int r = x(6, 6);
            MessageBox.Show(Convert.ToString(r));

        }

       
        //This method can be pointed to by the DoMath delegate
        public int Add(int x, int y)
        {
            return x+y;
        }

        //This method can be pointed to by the DoMath delegate
        public int Subtract(int x, int y)
        {
            return x - y;
        }

        //This method can NOT be pointed to by the DoMath delegate
        //because it has a different signature (only one argument)
        public string Test(string y)
        {
            return "Test method";
        }
    }

No comments:

Post a Comment

BidVertiser

pocket cents

PocketCents Local Online Advertising