Loading ...

Delegates in C#.

Who is online?  0 guests and 0 members
home  »  forums   »  asp.net topics   »  getting started / general asp.net   » Delegates in C#.

Delegates in C#.

Posts under the topic: Delegates in C#.

Posted: 10/25/2010

Contributor 2237  points  Contributor
  • Joined on: 9/24/2009
  • Posts: 172

Hello Experts,

I have created a simple Delegates.Example -

using System;
using System.IO;

namespace ConsoleApplication2
{
   
    public class MyClass
    {
        public delegate void MyDelegate();

        public void Process(MyDelegate myDelegate)
        {
            if (myDelegate!=null)
            {
                Console.WriteLine("Delegate");
            }
        }
    }

   
    public class TestApplication
    {
        public void MyTest()
        {
            Console.WriteLine("My Test Method");
        }

        static void Main(string[] args)
        {
            TestApplication testApplication = new TestApplication();

            MyClass myClass = new MyClass();

            MyClass.MyDelegate myDelegate = new MyClass.MyDelegate(testApplication.MyTest);
            myClass.Process(myDelegate);
            Console.ReadLine();
        }
    }
}

 

Output -

Delegate

Can anyone tell me why My Test Method is not print?

 


Posted: 2/8/2011

Professional 8505  points  Professional
  • Joined on: 5/3/2010
  • Posts: 391
  Answered

I really don't know how we missed this out.

Emm... it's because you actually call the Process(delegate) method explicitly. Since delegate won't be null as you already add myDelegate as parameter to the Process method, the "Delegate" will be print. You don't really call MyTest() method.

It will be printed, if you add

        public MyClass()
        {
            TestApplication t = new TestApplication();
            t.MyTest();
        }


Inside MyClass.

Hope this helps.


Posted: 2/10/2011

Contributor 2237  points  Contributor
  • Joined on: 9/24/2009
  • Posts: 172

Thank you Hajan.


Posted: 2/10/2011

Professional 8505  points  Professional
  • Joined on: 5/3/2010
  • Posts: 391

mohit kumar said:

Thank you Hajan.

You are always welcome Wink!


Page 1 of 1 (4 items)