Tuesday, October 27, 2009

Simple Delegate example in C#


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

namespace DelegateExample
{
    public class Program
    {
      
        public delegate int Calculate(int a,int b);
        static void Main(string[] args)
        {
            myClass objMC;
            objMC = new myClass();
            // Creating objects / instances of delegate and assigning them methods of myClass
            Calculate add = new Calculate(objMC.add);
            Calculate sub = new Calculate(objMC.sub);

            // Calling myclass methods via delegate
            Console.WriteLine("2  + 3 =" + add(2, 3));
            Console.WriteLine("10  - 3 =" + sub(10, 3));
            Console.ReadLine();

  

        }
    }

    public class myClass
    {
        public myClass()
        {
        }
        public int add(int n1, int n2)
        {
            return n1 + n2;
        }
        public int sub(int n1, int n2)
        {
            return n1 - n2;
        }
    }
   
}

No comments:

Post a Comment

Followers

Search This Blog