Solved

Events and Delegates

Posted on 2009-04-04
18
758 Views
Last Modified: 2013-12-17
HI!

I have a question regarding events and delegates.
What d the difference between using a delegate type for an event or not?

When should I use the delegate event and when should I not?

Not sure I understand the text I read on msdn.
0
Comment
Question by:AWestEng
  • 9
  • 4
  • 2
  • +3
18 Comments
 
LVL 4

Assisted Solution

by:brawney
brawney earned 20 total points
Comment Utility
A delegate is a class that refers to a method of a class.  If you're familiar with good old C stuff, you can think of it as a pointer.

See if this article helps - http://www.aspfree.com/c/a/C-Sharp/C-Sharp-Delegates-Explained/
0
 
LVL 62

Expert Comment

by:Fernando Soto
Comment Utility
Hi AWestEng;

To the question, "What is the difference between using a delegate type for an event or not?", One is working with delegates in this form involves some routine steps such as defining the delegate, declaring some variables, and creating registration / unregistration method to handle the list of morphed that will be called when an event is fired. As a short cut to doing the above C# provides the event keyword. When you compile a program that uses the event keyword the compiler automatically builds the delegate, the registration / unregistration methods as well as any other variables that is needed. The event keyword is known as syntactic sugar.  

To the question, "When should I use the delegate event and when should I not?", Use the event keyword when ever you can.

Fernando
0
 
LVL 62

Accepted Solution

by:
Fernando Soto earned 350 total points
Comment Utility
Hi AWestEng;

Had a spelling error on the last post re-posting.

To the question, "What is the difference between using a delegate type for an event or not?", One is working with delegates in this form involves some routine steps such as defining the delegate, declaring some variables, and creating registration / unregistration method to handle the list of methods that will be called when an event is fired. As a short cut to doing the above C# provides the event keyword. When you compile a program that uses the event keyword the compiler automatically builds the delegate, the registration / unregistration methods as well as any other variables that is needed. The event keyword is known as syntactic sugar.  

To the question, "When should I use the delegate event and when should I not?", Use the event keyword when ever you can.

Fernando
0
 
LVL 1

Author Comment

by:AWestEng
Comment Utility
I'm not sure I understand.

Something like this maybe?

So a delegate is always assigned to an event? (When it compiles)
 
In Vb.Net I can do this

Private Event ExecuteStateMachineEvent()  
But here I don't have any delegate!?
But when using AddHandler, is the delegate created then?
 
But I can also can do this

Private Delegate Sub TestDelegate()  
Private Event TestEvent as TestDelegate
Is there any diffrens bwtween these two, does not the AddHandler suff do the same?

 
In C# I can't do the same, here I must assign a delegate to the event, isn't that right?

public delegate void EventDataUpdatedDelegate();
public event EventDataUpdatedDelegate EventDataUpdated;  
So to my question ,when I should use a event with a delegate or not, is not exactly valid then? I always use a deleagte, but in VB I don't need to declare one, the addhandler and AddressOf fixes that?
Have I understand it correct?
 
0
 
LVL 6

Assisted Solution

by:SaedSalman
SaedSalman earned 30 total points
Comment Utility
A delegate is an object that refers to a static method or an instance method.
A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked. Unlike function pointers in C or C++, delegates are object-oriented, type-safe, and secure.
Advantages:
.Encapsulating the method's call from caller
.Effective use of delegate improves the performance of application.
.Used to call a method asynchronously.

have you seen this ?
http://msdn.microsoft.com/en-us/library/aa288459(VS.71).aspx

For delegate and event:
http://www.codersource.net/csharp_delegates_events.html
http://www.akadia.com/services/dotnet_delegates_and_events.html

>So a delegate is always assigned to an event ?
>In C# I can't do the same, here I must assign a delegate to the event, isn't that right?
Nope, its assigned to a method that mights be an event handler. it is your choise.

0
 
LVL 1

Author Comment

by:AWestEng
Comment Utility
but a eventhandler is a "delegate"
http://msdn.microsoft.com/en-us/library/system.eventhandler.aspx
so then it it always a delegate then?
0
 
LVL 1

Author Comment

by:AWestEng
Comment Utility
and if the event doesn't not always use a type of delegate i still don't understand when I should use
Private Delegate Sub TestDelegate()  
Private Event TestEvent as TestDelegate
or when I only should use
 Private Event TestEvent
0
 
LVL 1

Author Comment

by:AWestEng
Comment Utility
spelling error>  

and if the event doesn't always use a type of delegate I still don't understand when I should use

Private Delegate Sub TestDelegate()  
Private Event TestEvent as TestDelegate

or when I only should use

Private Event TestEvent  
0
 
LVL 74

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 80 total points
Comment Utility
You can use delegates as callbacks. Say you have a function that does some work. While you are in the middle of processing, you would like to display a message to the user.

Now before we display the message to the user, let's say you have two other functions in your application which display two different messages when called. But you only have one worker function. You can have a delegate method as a parameter that gets called when you get to the notification part of your code.

So depending on how you call the worker function, different messages will be called.
'Declare delegate type

Private Delegate Sub ShowMessage()
 

Private Sub CallingFunction()

    'Call function with first message

    WorkerFunction(AddressOf MessageOne)
 

    'Call function with second message

    WorkerFunction(AddressOf MessageTwo

End Sub
 

Private Sub WorkerFunction(ByVal del as ShowMessage)

    'Imitate work

    System.Threading.Thread.Sleep(10000)
 

    'Show a message

    del.Invoke()
 

    'Imitate some more work

    System.Threading.Thread.Sleep(1000)

End Sub
 

Private Sub MessageOne()

    MessageBox.Show("This is the first message.")

End Sub
 

Private Sub MessageTwo()

    MessageBox.Show("This is the second message.")

End Sub

Open in new window

0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 74

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 80 total points
Comment Utility
Events are also callbacks. The reason they are known as events is to tie in with the object-oriented concept--an object does things and things happen to an object (events). When an event is raised, the code breaks off into the function that is associated with the event--the event handler. Once the handler completes, execution returns to the point following where the code broke off.
0
 
LVL 1

Author Comment

by:AWestEng
Comment Utility
Ok, I think I understand the delegate stuff.
so if I don't use a delegate for the event I can't "connect" methods to this event?
so when is this any good?
 
Private Event TestEvent  
0
 
LVL 2

Assisted Solution

by:jonathan_mccoy
jonathan_mccoy earned 20 total points
Comment Utility
an event has a signature correct
a delegate is that signature

so you can make a delegate yes but in the most basic of code it is just a signature

you have a delegate & an event with the delegate's signature

so you find a method that has the same signature as the delegate and you add it

an event hold's delegates & it has a signature defined by a delegate

I could do VB.NET ex code if you wish
public delegate void d(); 

public event d myEvent;
 

public void doStuff()

{//stuff

}

public void main()

{ 

     myEvent += new d(doStuff);

}

Open in new window

0
 
LVL 1

Author Comment

by:AWestEng
Comment Utility
the stuff that make me confused is this..  
Check the code,
Two "diffrent" cases
It does the same thing, does it not?
So my question here is, why ever use the delegate in this case?

Public Class Form1
 

    Public test As New Class1
 

    Public Sub New()
 

        ' This call is required by the Windows Form Designer.

        InitializeComponent()
 

        ' Add any initialization after the InitializeComponent() call.
 

        AddHandler test.TestEvent1, AddressOf TestSub
 

        AddHandler test.TestEvent2, AddressOf TestSub2

    End Sub
 

    Private Sub TestSub()

        MessageBox.Show("Event1")

    End Sub
 

    Private Sub TestSub2()

        MessageBox.Show("Event2")

    End Sub
 

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        test.Test()

    End Sub
 

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

        test.Test2()

    End Sub

End Class
 

Public Class Class1
 

    ' case 1

    Public Event TestEvent1()
 

    ' case 2

    Public Delegate Sub TestDelegate()

    Public Event TestEvent2 As TestDelegate
 

    Public Sub Test()

        RaiseEvent TestEvent1()

    End Sub
 

    Public Sub Test2()

        RaiseEvent TestEvent2()

    End Sub

End Class

Open in new window

0
 
LVL 1

Author Comment

by:AWestEng
Comment Utility
I think I found it,
case 1
the compiler  declares a delegate implicitly, so there is a delegate, but I don't need to declare it explicitly.
Here is the IL code for case 1 and case 2.
And here I can see (IL code) that the compiler has added a delegate to the event (Eventhandler) in case 1 too.
That was the stuff I was confused about, I thought you could declare events without using some sort of delegate in the end, but that was not the case. it ALWAYS uses a delegate when the event is connected to a "listner".

Case 1

.method public specialname instance void 

        add_TestEvent1(class EventStuff.Class1/TestEvent1EventHandler obj) cil managed synchronized

{

  .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) 

  // Code size       25 (0x19)

  .maxstack  8

  IL_0000:  ldarg.0

  IL_0001:  ldarg.0

  IL_0002:  ldfld      class EventStuff.Class1/TestEvent1EventHandler EventStuff.Class1::TestEvent1Event

  IL_0007:  ldarg.1

  IL_0008:  call       class [mscorlib]System.Delegate [mscorlib]System.Delegate::Combine(class [mscorlib]System.Delegate,

                                                                                          class [mscorlib]System.Delegate)

  IL_000d:  castclass  EventStuff.Class1/TestEvent1EventHandler

  IL_0012:  stfld      class EventStuff.Class1/TestEvent1EventHandler EventStuff.Class1::TestEvent1Event

  IL_0017:  nop

  IL_0018:  ret

} // end of method Class1::add_TestEvent1
 
 

Case 2

.method public specialname instance void 

        add_TestEvent2(class EventStuff.Class1/TestDelegate obj) cil managed synchronized

{

  .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) 

  // Code size       25 (0x19)

  .maxstack  8

  IL_0000:  ldarg.0

  IL_0001:  ldarg.0

  IL_0002:  ldfld      class EventStuff.Class1/TestDelegate EventStuff.Class1::TestEvent2Event

  IL_0007:  ldarg.1

  IL_0008:  call       class [mscorlib]System.Delegate [mscorlib]System.Delegate::Combine(class [mscorlib]System.Delegate,

                                                                                          class [mscorlib]System.Delegate)

  IL_000d:  castclass  EventStuff.Class1/TestDelegate

  IL_0012:  stfld      class EventStuff.Class1/TestDelegate EventStuff.Class1::TestEvent2Event

  IL_0017:  nop

  IL_0018:  ret

} // end of method Class1::add_TestEvent2

Open in new window

0
 
LVL 62

Expert Comment

by:Fernando Soto
Comment Utility
To your statement, "the compiler  declares a delegate implicitly, so there is a delegate, but I don't need to declare it explicitly.", The point of my post above was just that.
0
 
LVL 1

Author Comment

by:AWestEng
Comment Utility
I did not get that the first time I read it.. hehe..
but when reading it again... ,you are quit right there.. :)
thx man
0
 
LVL 1

Author Closing Comment

by:AWestEng
Comment Utility
Thx guys!
0
 
LVL 62

Expert Comment

by:Fernando Soto
Comment Utility
Not a problem, always glad to help.  ;=)
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Suggested Solutions

Welcome my friends to the second instalment and follow-up to our Minify and Concatenate Your Scripts and Stylesheets (http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/A_4334-Minify-and-Concatenate-Your-Scripts-and-Stylesheets.html)…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now