locked
method calling using delegate RRS feed

  • Question

  • User-922170241 posted

    HI to all , thanks in advance

    I have a class ,which has one method .

    i can call that method using class instantiation and by using delagte .

    what is the difference between the two types of calling ?

    In which situation we can use delegate.?

    class TestDelegate
        {
              public void CallFunction()
            {
                Console.WriteLine("Function Called");
            }

    }

    class Program
        {
            public delegate void SimpleDelegate();
            static void Main(string[] args)
            {
                TestDelegate obj = new TestDelegate();
                obj.CallFunction();


                SimpleDelegate sd1 = new SimpleDelegate(obj.CallFunction);
                sd1.Invoke();
                Console.Read();

            }
        }



    Sunday, October 16, 2011 2:08 PM

Answers

  • User-578657687 posted

    Hi,

    You can retrieve the idea from this post:

    http://social.msdn.microsoft.com/forums/en-us/csharpgeneral/thread/581C8E9B-0EAA-4DA2-BE65-B99732CA7D2D

    You need to konw, when you call one method using a class instance, this called method must be the member of class.

    Using delegate to call one method(instance method/static method), the delegate has a pointer to this method and the delegate uses this pointer to find the method and execute it.

    When you can use delegate? For example: You have a task which you needn't to do it by yourself, so you need to assign it to others, every one works on the part of task. I assume that each one is a method, now you can use the delegate to call these method to complete the task. Also you can use a class including multiple methods to do that, but the delegate meets the OOP better.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, October 19, 2011 5:33 AM