Delegates in C#

Here’s a simple tutorial on how to use Delegates in C#. It’s mostly self explanatory, so no futher comments


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

namespace DelegateTutorial
{

    public class SaySomeThing
    {
        internal string s1 = "foo";
        internal string s2 = "bar";
        internal string s3 = "wow";
    }

    public delegate void MyDelegate(SaySomeThing s);
    public delegate void MyOtherDelegate(SaySomeThing s, int num);

    class Program
    {
        public void overloadDelegate1(SaySomeThing s)
        {
            Console.WriteLine(s.s1);
        }

        public void overloadDelegate2(SaySomeThing s)
        {
            Console.WriteLine(s.s2);
        }

        public static void overloadDelegate3(SaySomeThing s)
        {
            Console.WriteLine(s.s2);
        }

        public static void overloadDelegate4(SaySomeThing s, int num)
        {
            for (int j = 0; j < num; j++)
                Console.WriteLine(s.s3);
        }

        public void callDelegate(MyDelegate mydelegate)
        {
            SaySomeThing something = new SaySomeThing();
            mydelegate(something);
        }

        public void callDelegate2(MyOtherDelegate myotherdelegate, int num)
        {
            SaySomeThing something = new SaySomeThing();
            myotherdelegate(something, num);
        }

        static void Main(string[] args)
        {
            Program p = new Program();
            p.callDelegate(new MyDelegate(p.overloadDelegate1));
            p.callDelegate(new MyDelegate(p.overloadDelegate2));
            p.callDelegate(new MyDelegate(Program.overloadDelegate3));
            p.callDelegate2(new MyOtherDelegate(Program.overloadDelegate4), 5);

            Console.WriteLine("******************");
            //alternatively
            MyDelegate d1 = new MyDelegate(p.overloadDelegate1);
            d1(new SaySomeThing());
            MyDelegate d3 = new MyDelegate(Program.overloadDelegate3);
            d3(new SaySomeThing());
            Console.WriteLine();
            MyDelegate dc = d1 + d1 + d3 + d3;
            dc(new SaySomeThing());

        }
    }
}

~ by vinaybalamuru on March 5, 2009.

Leave a Reply

You must be logged in to post a comment.