hi all:)
i got confused in this point:(
i have questions that i don't understand it well
knowing that i have searched a lot but i don't know i didn't understand it yet
1-when it is really impossible to work in a
program without a delegate (please give a simple example)?
2-what is the difference between delegates and calling a function?
3-and i know that delegates can refer to multiple methods so when i invoke it all of them will work so does the threads enter this field:-/ and how ?
4-what is the benefits of the Anonymous Methods ? (please give example in a program)
5-can i run the delegate without method invoker???
del(1);
for example and when to use method invoker
and sorry for wasting ur time but it will be a generosity of you if u could answer these questions please

Recommended Answers

All 21 Replies

hi all:)
i got confused in this point:(
i have questions that i don't understand it well
knowing that i have searched a lot but i don't know i didn't understand it yet
1-when it is really impossible to work in a
program without a delegate (please give a simple example)?
- when you want to pass function to another function as a parameter
2-what is the difference between delegates and calling a function?
delegate is a variable that keeps information about the function, it has the address of that function. it enables you to wrap and encapsulate methods(functions) into a single entity.3-and i know that delegates can refer to multiple methods so when i invoke it all of them will work so does the threads enter this field:-/ and how ?
-although this is a question for Narue(Julienne Walker), i think it does not execute them at the same time, but one after the other.4-what is the benefits of the Anonymous Methods ? (please give example in a program)
- Some times you want to perform some actions, but you dont want to create a seperate function for those actions because you know that you are going to use it just for once. In those cases you encapsulate that actions into an anonymous function and call them using a delegate, it is anonymous because you are not going to call it again, so you dont need to name it.5-can i run the delegate without method invoker???
del(1);
for example and when to use method invoker
and sorry for wasting ur time but it will be a generosity of you if u could answer these questions please
- Yes you can, methodinvoker just saves you from additional coding. it enables you to call methods anonymously.

commented: thorough answer +9

1-when it is really impossible to work in a program without a delegate (please give a simple example)?
>> Never really. Delegates are provided for convenience of calling. For example the Button's Click event is defined in the .NET Framework and by using a delegate any assembly that uses the .NET framework can utilize's the button's click event. This also means that delegates make your assemblies extendible to other assemblies with having no knowledge of how the caller intends to call the code.

>> what is the difference between delegates and calling a function?
As Serkan pointed out the delegate is a method's memory address. When you call a delegate you know you're calling something with the same method signature but it may in fact be an EventHandler or a Delegate[] with multiple methods. So in this case you could actually cause two methods to be invoked, where as with a method it will be a single call.
(C# does not have functions, they are all methods)

Example of calling a delegate which executes two methods. Here is a class implementing a delegate:

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

namespace daniweb
{
  public delegate void OnDelegateEvent(object sender, DelegateEventArgs e);

  public class SomeDelegateImplementation
  {
    public event OnDelegateEvent OnEvent;
    public SomeDelegateImplementation()
    {
    }
    public void DoWork()
    {
      if (this.OnEvent != null)
      {
        DelegateEventArgs args = new DelegateEventArgs();
        Console.WriteLine(string.Format("Firing event(s): {0:G}", DateTime.Now));
        this.OnEvent(this, args);
        Console.WriteLine(string.Format("Events fired: {0:G}", DateTime.Now));
      }
    }
  }
  public class DelegateEventArgs : EventArgs
  {
    private bool _handled;

    public bool Handled
    {
      get { return _handled; }
      set { _handled = value; }
    }
    public DelegateEventArgs()
    {
    }
  }
}

Then calling it:

private void button2_Click(object sender, EventArgs e)
    {
      SomeDelegateImplementation s = new SomeDelegateImplementation();
      Delegate d = Delegate.Combine(new OnDelegateEvent(del_OnEvent), new OnDelegateEvent(del_OnEvent2));
      s.OnEvent += (OnDelegateEvent)d;
      s.DoWork();
    }
    
    void del_OnEvent(object sender, DelegateEventArgs e)
    {
      System.Threading.Thread.Sleep(1000);
      Console.WriteLine(string.Format("Event 1: {0:G}", DateTime.Now));
    }

    void del_OnEvent2(object sender, DelegateEventArgs e)
    {
      System.Threading.Thread.Sleep(1000);
      Console.WriteLine(string.Format("Event 2: {0:G}", DateTime.Now));
    }

Results in:

Firing event(s): 8/28/2009 8:32:12 PM
Event 1: 8/28/2009 8:32:13 PM
Event 2: 8/28/2009 8:32:14 PM
Events fired: 8/28/2009 8:32:14 PM

>>can i run the delegate without method invoker???
See the above code

Yeah the difference between sknake and me is, he is full time student whereas i am full time employee. that explains why he is able to provide code and i am not. we will see him right after he starts to work as full time.

hi all:)
i got confused in this point:(
i have questions that i don't understand it well
knowing that i have searched a lot but i don't know i didn't understand it yet
1-when it is really impossible to work in a
program without a delegate (please give a simple example)?
- when you want to pass function to another function as a parameter
2-what is the difference between delegates and calling a function?
delegate is a variable that keeps information about the function, it has the address of that function. it enables you to wrap and encapsulate methods(functions) into a single entity.3-and i know that delegates can refer to multiple methods so when i invoke it all of them will work so does the threads enter this field:-/ and how ?
-although this is a question for Narue(Julienne Walker), i think it does not execute them at the same time, but one after the other.4-what is the benefits of the Anonymous Methods ? (please give example in a program)
- Some times you want to perform some actions, but you dont want to create a seperate function for those actions because you know that you are going to use it just for once. In those cases you encapsulate that actions into an anonymous function and call them using a delegate, it is anonymous because you are not going to call it again, so you dont need to name it.5-can i run the delegate without method invoker???
del(1);
for example and when to use method invoker
and sorry for wasting ur time but it will be a generosity of you if u could answer these questions please
- Yes you can, methodinvoker just saves you from additional coding. it enables you to call methods anonymously.

Thanks serkan sendur for your help would you mind if i have questions on your answers.
first on your answer on the first question :
1-when I want to pass function to another function as a parameter?
2-so the only difference is that it can invoke more than one method right?

1-when it is really impossible to work in a program without a delegate (please give a simple example)?
>> Never really. Delegates are provided for convenience of calling. For example the Button's Click event is defined in the .NET Framework and by using a delegate any assembly that uses the .NET framework can utilize's the button's click event. This also means that delegates make your assemblies extendible to other assemblies with having no knowledge of how the caller intends to call the code.

thanks sknake for ur help but i didn't understand this answer can u explain it in another way sorry for bothering

Perhaps this snippet will shed a light on how to pass methods(in this case math functions: Hi Scott;) ) as a parameter to other methods.

Perhaps this snippet will shed a light on how to pass methods(in this case math functions: Hi Scott;) ) as a parameter to other methods.

thanks ddanbe but in this code we can pass a method that returns a double no need to make a delegate why we use delegate here:?: ?

    // Integrate a function by calculating the surface under a curve by using rectangles.
    // Just exercising the delegate functions here
    // Not a super way to do it, but it works in explaining delegates(I hope)
    // The higher the "parts" the better the integration.
    public static double IntegrateRect(double a, double b, int parts, function F)
    {
        double width = (b - a) / parts;
        double integral = 0.0;

        for (int i = 1; i <= parts; i++)
        {
            integral += width * F(a - 0.5 * width + i * width);
        }
        return integral;
    }

I would even say it is essential and necessary to use delegates in this case!
You integrate a function F (calculate the area under the curve between values a and b)
You cannot give the integrate method one value(a double) to do it's thing, you must give it the whole function. Otherwise you would have things like IntegrateMySquareFunction, IntegrateMyOtherSquareFunction, IntegrateMyParabolicFunction etc.
Here you have a method who knows how to integrate. Just feed it any continuous function between a and b and it will give you an answer.
The double you are reffering to gets calculated every time in the line integral += width * F(a - 0.5 * width + i * width);
(look at the F) F represents any delegate function here.

thanks sknake for ur help but i didn't understand this answer can u explain it in another way sorry for bothering

I think serkan and danny have this thread under control. I'll probably confuse you more, they're doing a great job of explaining :P

I think serkan and danny have this thread under control. I'll probably confuse you more, they're doing a great job of explaining :P

No, when i said you post code samples, it was a praise. I definitely think that you are more helpful. I am usually tired and yesterday i was at office until 10 pm, during that time i said, after you start to work full time, it becomes harder to post sample code.
There was no offence or madness :)
Please dont think i or danny dominate the thread, as i said, for me you are the most helpful poster in c# forum.

I would even say it is essential and necessary to use delegates in this case!
You integrate a function F (calculate the area under the curve between values a and b)
You cannot give the integrate method one value(a double) to do it's thing, you must give it the whole function. Otherwise you would have things like IntegrateMySquareFunction, IntegrateMyOtherSquareFunction, IntegrateMyParabolicFunction etc.
Here you have a method who knows how to integrate. Just feed it any continuous function between a and b and it will give you an answer.
The double you are reffering to gets calculated every time in the line integral += width * F(a - 0.5 * width + i * width);
(look at the F) F represents any delegate function here.

thanks a lot guys really u are so helpful
ok i have a question if the delegate function was declared as public would we be in need to pass it as a parameter to the method???

Why would you be in NEED to pass a delegate to a method because it is public?

Why would you be in NEED to pass a delegate to a method because it is public?

so ur answer is we wouldn't be in need right?

You pass a method to a method because you want to do so, not because you must. For example I passed in the sine function to the integrate method because I wanted to know what the area was between 1 and 2 under the sine curve.(yeah this is getting freaky I know:icon_mrgreen: )

You pass a method to a method because you want to do so, not because you must. For example I passed in the sine function to the integrate method because I wanted to know what the area was between 1 and 2 under the sine curve.(yeah this is getting freaky I know:icon_mrgreen: )

:'( if the data member was declared as public so it is no need to pass it as a parameter in a method right or not ?i think it is the same with the delegate?
thanks for ur patience with me

I understand now what you mean.
If you use public methods like Math.Sine, you still have to write many integrate methods for every math function you want to integrate. With delegates you only have to write one such method.
In this case (integration) there are different methods on how to integrate a math function, trapezodial rule for instance. Then your integration method would be different, but you would still do it with delegates. Hope this makes it clear.:)

I understand now what you mean.
If you use public methods like Math.Sine, you still have to write many integrate methods for every math function you want to integrate. With delegates you only have to write one such method.
In this case (integration) there are different methods on how to integrate a math function, trapezodial rule for instance. Then your integration method would be different, but you would still do it with delegates. Hope this makes it clear.:)

THANKS ddanbe a lot
ok can any one suggests a tutorials which are simple
knowing that i have read many pages on the net if u have found something on books which is describing delegates in a simple way please notify me with the name of the book and thanks a lot all for ur great help with me

the best way to understand delegates is to have some knowledge about C. search for C function pointers, and you will have a good understanding of this delegate concept. It takes a while till you see it in action. Interfaces are also like that, you understand why they are useful when you see them in use.

the best way to understand delegates is to have some knowledge about C. search for C function pointers, and you will have a good understanding of this delegate concept. It takes a while till you see it in action. Interfaces are also like that, you understand why they are useful when you see them in use.

thanks serkan sendur a lot

you are very welcome

please mark as solved if your problem is solved.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.