Tech Off Thread

34 posts

Forum Read Only

This forum has been made read only by the site admins. No new threads or comments can be added.

Real-World application of Delegates...

Back to Forum: Tech Off
  • User profile image
    jsampsonPC

    When I was interviewing for my current job I had to go through a series of steps. Mutliple interviews with multiple people from the organization. One of them (the second interview) was a "Technical" interview, which seemed more like an interrogation Smiley

    I had to answer questions regarding OOP, JavaScript, PHP, VB.NET, C# - etc. I was doing fine until one of the interviewers asked, "Jonathan, what is a delegate?" I quickly responded, "I believe it is used in threading for delegating processes." I had read a tutorial about mutli-threaded apps inwhich delegates were mentioned, but I didn't know for sure what they were.

    So I just sat down in the "reading room" and read in my VS2005 book a section on Delegates, and it left me wondering why we need them - what are they used for? Why not refer directly to functions and subs, why go through some middle-man?

    I'm still very new to many things .NET, so excuse my ignnorance Smiley

  • User profile image
    Cannot​Resolve​Symbol

    jsampsonPC wrote:
    When I was interviewing for my current job I had to go through a series of steps. Mutliple interviews with multiple people from the organization. One of them (the second interview) was a "Technical" interview, which seemed more like an interrogation Smiley

    I had to answer questions regarding OOP, JavaScript, PHP, VB.NET, C# - etc. I was doing fine until one of the interviewers asked, "Jonathan, what is a delegate?" I quickly responded, "I believe it is used in threading for delegating processes." I had read a tutorial about mutli-threaded apps inwhich delegates were mentioned, but I didn't know for sure what they were.

    So I just sat down in the "reading room" and read in my VS2005 book a section on Delegates, and it left me wondering why we need them - what are they used for? Why not refer directly to functions and subs, why go through some middle-man?

    I'm still very new to many things .NET, so excuse my ignnorance Smiley


    According to the VS help, it allows you to encapsulate methods like you would with an interface (so you don't have to know anything about the implementation), but it allows you to do such things as encapsulate static methods or allow a class to have more than one implementation of a method.

    I can't get onto MSDN right now (ISP or school network issues), but here's the address from VC#EE 2005 help (don't know if this helps or not):

    When to Use Delegates Instead of Interfaces
    ms-help://MS.VSExpressCC.v80/MS.NETFramework.v20.en/dv_csref/html/2e759bdf-7ca4-4005-8597-af92edf6d8f0.htm

  • User profile image
    cheong

    It's good when designing components when you're designing an event and wish to specify what "function signature" the event handler should have. (like what parameter it should expect etc.)

    Recent Achievement unlocked: Code Avenger Tier 4/6: You see dead program. A lot!
    Last modified
  • User profile image
    Minh

    V is a delegate tae-Estep-it more --- 10 v.-st? multi Zoë-aft 1-1.10=-7+2 30 Exe Ver.-Jo-fetus 193 "F

  • User profile image
    Minh

    cow v.-ht-st (type-safe-to) outputs _ if f3 is diff 40 Exe Va.-re--erotize. with the Same input & @ Ex-v.-ea.-effuses. But I want ft Elf? GOV.-I-OS/2 I wanna... onsides E: 58 ré -sf1 .

  • User profile image
    Minh

    oidia ratel. to Duper Object Leg Secret Weapon. oidia notification % anise Done But wait... there's more... _ _ ~ _ _ _ _ (event) it 2-1=0

  • User profile image
    Minh

    foam it: It*' Io. o* decagons. st-é "t.) - oh-bead

  • User profile image
    Ang3lFir3

    Minh wrote:
    foam it: It*' Io. o* decagons. st-é

    I was getting that Impression...

  • User profile image
    Ang3lFir3

    jsampsonPC wrote:
    When I was interviewing for my current job I had to go through a series of steps. Mutliple interviews with multiple people from the organization. One of them (the second interview) was a "Technical" interview, which seemed more like an interrogation Smiley

    I had to answer questions regarding OOP, JavaScript, PHP, VB.NET, C# - etc. I was doing fine until one of the interviewers asked, "Jonathan, what is a delegate?" I quickly responded, "I believe it is used in threading for delegating processes." I had read a tutorial about mutli-threaded apps inwhich delegates were mentioned, but I didn't know for sure what they were.

    So I just sat down in the "reading room" and read in my VS2005 book a section on Delegates, and it left me wondering why we need them - what are they used for? Why not refer directly to functions and subs, why go through some middle-man?

    I'm still very new to many things .NET, so excuse my ignnorance Smiley


    maybe this can help a little...

    http://dnrtv.com/default.aspx?showID=40

  • User profile image
    AndyC

    Delegates provide all the cool functionality that would have been lost by removing function pointers, but in a nice type-safe way.

  • User profile image
    littleguru

    Short answer: Delegates are type safe function pointers.

    What's a function pointer? A function pointer is (in C, C++, and other languages) a pointer (on 32 bit computers a 32 bit integer) to a method. This pointer can be used as a normal method. You can call it, set parameters etc.

    Why are they type safe? In .NET everything is type safe. Expect __ComObject - but that's another story.

    You are always using them! Where? Events! Events in .NET are a typical case for delegates. You register a method that is called when something happens. That's the registration of a delegate. Better of a multicast delegate. Means one event can trigger more then one method. In easier words one delegate can point to more then one method (2, 3, 4, ...).

  • User profile image
    littleguru

    But you can do even more with delegates in .NET. That's the multithreading with delegtaes (that's also what you read about it).

    You can call each delegate in a async way. In that case the method (remember delegate = method pointer) is called in a new thread. That thread is only created for this call - it is taken from a thread pool, but it's only used for this call.

    That's why you need it when manipulating a UI control from another thread. If the UI runs in another thread then the method that is manipulating the UI, it could block the UI thread. The asynch way avoids that problem.

  • User profile image
    Massif

    Not to mention that Delegates also store a reference to the object on which to call the method you specified. (that makes no sense, sorry - in short if you create a delegate it knows which object to call the method on. Whereas in C++ if you use a function pointer you don't know which object to call the function on.)

    Which is totally awesome, and saves having to keep track on which objects you wanted to respond to the call. (I got lost on the diagrams, Minh may have mentioned that already.)

  • User profile image
    jsampsonPC

    Hey thanks guys - especially you, Minh (Wrist hurtin' yet?)

    From what I have gathered, they're just an easy way of calling mutliple object methods, without having to keep track of the object names.

    Yes? No?

    So the layout would look like this

        the delegate(Arg 1, Arg 2)

           run object1Method(Arg1, Arg2)

           run object2Method(Arg2)

        end delegate


    And I could call my delegate anywhere in code

        delegate("Jonathan", "www.SampsonResume.com")

    Which would run both values through object1's Method, and only the webaddress through object2's Method.

    Am I getting this properly?

  • User profile image
    Sven Groot

    No, a delegate represents methods with only one specific signature.

    For instance I can make a delegate like this:
    C#: public delegate int MyDelegate(string x, string y);
    VB: Public Delegate Function MyDelegate(ByVal x As String, ByVal y As String) As Integer

    This delegate can represent only methods that have that exact signature: takes two string parameters, returns an int. If I have a function like this:
    C#: private int Foo(string x, string y);
    VB: Private Function Foo(ByVal x As String, ByVal y As String) As Integer

    I can now create an instance of MyDelegate that "points" to that function.
    C#: MyDelegate bar = new MyDelegate(Foo);
    VB: Dim bar As New MyDelegate(AddressOf Foo)

    Then I can call bar as if it was a function:
    Dim x As Integer = bar("hello", "world")

    This will end up calling Foo.

    You can also have multicast delegates: in this case, a delegate can point to more than one function. Calling the delegate calls all those functions in sequence. But, they must all have the same signature!

    You probably use multicast delegates a lot, even if you don't realize it. You see, events in .Net are really just multicast delegates. In C# this is a bit more obvious (VB hides it with the WithEvents/Handles syntax).

    That's also the main purpose for delegates: callback methods. You tell something else that some point in the future you'd like to be notified about something, and you specify which function should be called using a delegate. As you said in the original post, this is a common pattern in multithreaded programming: you start an asynchronous operation, passing it a delegate which it should call when the operation finishes.

  • User profile image
    jsampsonPC

    So then what distinguishes a delegate from a function with nested function-calling? From all that I've read so far, the same effect could be acheived with a function which passes its parameters to nested function-calls...

  • User profile image
    Massif

    A delegate lets you say "I'm going to call a function which looks like this <insert function definition>" and then wait for some other bit of code to say "here's the function you're going to call."

    This is how events work, when you raise the event you haven't implemented the functions (they're often implemented by a completely different piece of code altogether.) All you have to do is define a delegate (which is how events work after all) to say "any event handlers should look like this." and then when you're raising your event you just check to see if anyone's provided you with a function and then call it.

    Delegates are useful in the general case for you to provide all sorts of plug-in or callback methods.

    As an example, consider a generic class, you want to provide outside people with the ability to optionally perform some actions during your processing. All you need to do is provide a delegate, if they want to hook into your action to do their stuff they create a function which matches the delegate and give it to your class. Your class doesn't need to know anything at all about the function which has been provided, it just invokes the delegate.

    Is that clear? I'm not sure I'm making it clear. Anyway, the best real world example of delegates is Events, as they are just a special case of a delegate.

  • User profile image
    cokert

Conversation locked

This conversation has been locked by the site admins. No new comments can be made.