Solved

Events and Delegates

Posted on 2009-04-04
18
769 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
ID: 24067374
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
ID: 24067421
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
ID: 24067441
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
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 
LVL 1

Author Comment

by:AWestEng
ID: 24067518
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
ID: 24068364
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
ID: 24068414
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
ID: 24068436
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
ID: 24068449
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 75

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 80 total points
ID: 24068565
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
 
LVL 75

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 80 total points
ID: 24068582
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
ID: 24068674
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
ID: 24069836
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
ID: 24070938
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
ID: 24070989
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
ID: 24071625
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
ID: 24071644
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
ID: 31566565
Thx guys!
0
 
LVL 62

Expert Comment

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

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

It’s quite interesting for me as I worked with Excel using vb.net for some time. Here are some topics which I know want to share with others whom this might help. First of all if you are working with Excel then you need to Download the Following …
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
In this video I am going to show you how to back up and restore Office 365 mailboxes using CodeTwo Backup for Office 365. Learn more about the tool used in this video here: http://www.codetwo.com/backup-for-office-365/ (http://www.codetwo.com/ba…
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…

816 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

10 Experts available now in Live!

Get 1:1 Help Now