Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 789
  • Last Modified:

Events and Delegates

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
AWestEng
Asked:
AWestEng
  • 9
  • 4
  • 2
  • +3
6 Solutions
 
brawneyCommented:
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
 
Fernando SotoRetiredCommented:
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
 
Fernando SotoRetiredCommented:
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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
AWestEngAuthor Commented:
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
 
SaedSalmanCommented:
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
 
AWestEngAuthor Commented:
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
 
AWestEngAuthor Commented:
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
 
AWestEngAuthor Commented:
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
 
käµfm³d 👽Commented:
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
 
käµfm³d 👽Commented:
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
 
AWestEngAuthor Commented:
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
 
jonathan_mccoyCommented:
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
 
AWestEngAuthor Commented:
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
 
AWestEngAuthor Commented:
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
 
Fernando SotoRetiredCommented:
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
 
AWestEngAuthor Commented:
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
 
AWestEngAuthor Commented:
Thx guys!
0
 
Fernando SotoRetiredCommented:
Not a problem, always glad to help.  ;=)
0

Featured Post

Become an Android App Developer

Ready to kick start your career in 2018? Learn how to build an Android app in January’s Course of the Month and open the door to new opportunities.

  • 9
  • 4
  • 2
  • +3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now