Sunday 12 May 2013

C# - Simple Delegate Example



Create class
    public class DelegateSample
    {
        public delegate int Calculate(int n1, int n2);
        public int DoCalculations(int n1, int n2, Calculate myFunction)
        {
            return myFunction.Invoke(n1, n2);
        }

        public int Add(int n1, int n2)
        {
            return n1 + n2;
        }
        public int Multi(int n1, int n2)
        {
            return n1 * n2;
        }
    }

Now somewhere in code:

            DelegateSample s = new DelegateSample();
            int result1 = s.Add(10, 10);
            int result2 = s.Multi(10, 10);
            Response.Write(result1.ToString() + "<br />");
            Response.Write(result2.ToString());

No comments:

Post a Comment