473,832 Members | 2,137 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Delegates?

There are 2 ways to hook an event to a method. For example, to hook the
MouseEnter-event, you can use

MouseEnter+=OnM ouseEnter;

or

MouseEnter+=new System.EventHan dler(OnMouseHan dler);

Both work well, as demonstrated by the small program below, where the
MouseEnter-event is hooked the one way, the MouseLeave-event the other. What
is the preferred way to hook events to methods, and why?
//class Formclass Form:System.Win dows.Forms.Form { //data member label
System.Windows. Forms.Label label=new System.Windows. Forms.Label();
//constructor Form() { Controls.Add(la bel); MouseEnter+=OnM ouseEnter;
MouseLeave+=new System.EventHan dler(OnMouseLea ve); } //OnMouseEnter void
OnMouseEnter(Sy stem.Object a,System.EventA rgs b) {
label.Text="Mou seEntered"; } //OnMouseLeave void OnMouseLeave(Sy stem.Object
a,System.EventA rgs b) { label.Text="Mou seLeft"; } //Main [System.STAThrea d]
static void Main() { System.Windows. Forms.Applicati on.Run(new Form()); }}
Nov 21 '06 #1
7 1986
óeps, Linux style ;-) Here is the correct program:


//class Form
class Form:System.Win dows.Forms.Form
{
//data member label
System.Windows. Forms.Label label=new System.Windows. Forms.Label();
//constructor
Form()
{
Controls.Add(la bel);
MouseEnter+=OnM ouseEnter;
MouseLeave+=new System.EventHan dler(OnMouseLea ve);
}
//OnMouseEnter
public void OnMouseEnter(Sy stem.Object a,System.EventA rgs b)
{
label.Text="Mou seEntered";
}
//OnMouseLeave
public void OnMouseLeave(Sy stem.Object a,System.EventA rgs b)
{
label.Text="Mou seLeft";
}
//Main
[System.STAThrea d]
static void Main()
{
System.Windows. Forms.Applicati on.Run(new Form());
}
}


Nov 21 '06 #2
Hi Martijn,

The compiler simply checks that the signature for the OnMouseEnter method in
your first example matches the signature for the System.EventHan dler
delegate required by the MouseEnter event and swaps it with a call to
Delegate.Combin e, just like in the second example.

Personally, I like the first syntax better (it's new to the 2.0 framework).

--
Dave Sexton

"Martijn Mulder" <i@mwrote in message
news:45******** *************** @news.wanadoo.n l...
There are 2 ways to hook an event to a method. For example, to hook the
MouseEnter-event, you can use

MouseEnter+=OnM ouseEnter;

or

MouseEnter+=new System.EventHan dler(OnMouseHan dler);

Both work well, as demonstrated by the small program below, where the
MouseEnter-event is hooked the one way, the MouseLeave-event the other.
What is the preferred way to hook events to methods, and why?
//class Formclass Form:System.Win dows.Forms.Form { //data member label
System.Windows. Forms.Label label=new System.Windows. Forms.Label();
//constructor Form() { Controls.Add(la bel); MouseEnter+=OnM ouseEnter;
MouseLeave+=new System.EventHan dler(OnMouseLea ve); } //OnMouseEnter void
OnMouseEnter(Sy stem.Object a,System.EventA rgs b) {
label.Text="Mou seEntered"; } //OnMouseLeave void
OnMouseLeave(Sy stem.Object a,System.EventA rgs b) {
label.Text="Mou seLeft"; } //Main [System.STAThrea d] static void Main()
{ System.Windows. Forms.Applicati on.Run(new Form()); }}

Nov 21 '06 #3
Hi Martijn, I prefer the first way. The both compile to exactly the same
thang and, IMO, the conciseness does not make it less readable. In fact,
it makes it more readable because, normally, you don't care about the delegate
type that is being instantiated it. Also, because the code in the event handlers
is so simple, I might rewrite it like this:

//class Form
class Form: System.Windows. Forms.Form
{
//data member label
System.Windows. Forms.Label label =new System.Windows. Forms.Label();

//constructor
Form()
{
Controls.Add(la bel);
MouseEnter += delegate { label.Text = "MouseEnter ed"; };
MouseLeave += delegate { label.Text = "MouseLeft" ; };
}

//Main
[System.STAThrea d]
static void Main()
{
System.Windows. Forms.Applicati on.Run(new Form());
}
}

Best Regards,
Dustin Campbell
Developer Express Inc.
Nov 21 '06 #4
Martijn,

You didn't say what the problem was. There shouldn't be any problem because
the code generated by the c# compiler is exactly the same in both cases. It
has been added for convinience only. The preffered way is 'whatever makes
you code more readable'.

Execuse me for saying that, but please format a little your code snippets
before posting them. It is unreadable.
--
HTH
Stoitcho Goutsev (100)

"Martijn Mulder" <i@mwrote in message
news:45******** *************** @news.wanadoo.n l...
There are 2 ways to hook an event to a method. For example, to hook the
MouseEnter-event, you can use

MouseEnter+=OnM ouseEnter;

or

MouseEnter+=new System.EventHan dler(OnMouseHan dler);

Both work well, as demonstrated by the small program below, where the
MouseEnter-event is hooked the one way, the MouseLeave-event the other.
What is the preferred way to hook events to methods, and why?
//class Formclass Form:System.Win dows.Forms.Form { //data member label
System.Windows. Forms.Label label=new System.Windows. Forms.Label();
//constructor Form() { Controls.Add(la bel); MouseEnter+=OnM ouseEnter;
MouseLeave+=new System.EventHan dler(OnMouseLea ve); } //OnMouseEnter void
OnMouseEnter(Sy stem.Object a,System.EventA rgs b) {
label.Text="Mou seEntered"; } //OnMouseLeave void
OnMouseLeave(Sy stem.Object a,System.EventA rgs b) {
label.Text="Mou seLeft"; } //Main [System.STAThrea d] static void Main()
{ System.Windows. Forms.Applicati on.Run(new Form()); }}

Nov 21 '06 #5
Hi Stoitcho

:-) Thank you, I'll try to format a little. Also thanks for other posts that
you answered in a most helpfull way.

//class Form
class Form:System.Win dows.Forms.Form
{
//data member label
System.Windows. Forms.Label label=new System.Windows. Forms.Label();
//constructor
Form()
{
Controls.Add(la bel);
MouseEnter+=OnM ouseEnter;
MouseLeave+=new System.EventHan dler(OnMouseLea ve);
}
//OnMouseEnter
public void OnMouseEnter(Sy stem.Object a,System.EventA rgs b)
{
label.Text="Mou seEntered";
}
//OnMouseLeave
public void OnMouseLeave(Sy stem.Object a,System.EventA rgs b)
{
label.Text="Mou seLeft";
}
//Main
[System.STAThrea d]
static void Main()
{
System.Windows. Forms.Applicati on.Run(new Form());
}
}

Martijn,

You didn't say what the problem was. There shouldn't be any problem
because the code generated by the c# compiler is exactly the same in both
cases. It has been added for convinience only. The preffered way is
'whatever makes you code more readable'.

Execuse me for saying that, but please format a little your code snippets
before posting them. It is unreadable.
--
HTH
Stoitcho Goutsev (100)

"Martijn Mulder" <i@mwrote in message
news:45******** *************** @news.wanadoo.n l...
>There are 2 ways to hook an event to a method. For example, to hook the
MouseEnter-event, you can use

MouseEnter+=On MouseEnter;

or

MouseEnter+=ne w System.EventHan dler(OnMouseHan dler);

Both work well, as demonstrated by the small program below, where the
MouseEnter-event is hooked the one way, the MouseLeave-event the other.
What is the preferred way to hook events to methods, and why?
//class Formclass Form:System.Win dows.Forms.Form { //data member label
System.Windows .Forms.Label label=new System.Windows. Forms.Label();
//constructor Form() { Controls.Add(la bel); MouseEnter+=OnM ouseEnter;
MouseLeave+=ne w System.EventHan dler(OnMouseLea ve); } //OnMouseEnter void
OnMouseEnter(S ystem.Object a,System.EventA rgs b) {
label.Text="Mo useEntered"; } //OnMouseLeave void
OnMouseLeave(S ystem.Object a,System.EventA rgs b) {
label.Text="Mo useLeft"; } //Main [System.STAThrea d] static void Main()
{ System.Windows. Forms.Applicati on.Run(new Form()); }}


Nov 21 '06 #6
Also, one can consider doing the GUI in VB.Net. They're similar enough
that a coder should have no problem jumping from one to the other, and
if you're writing your GUI as a separate project from your logic, then
they can be in different languages anyways. VB.Net has the "Handles"
syntactic sugar that is very very nice.

Advantages of "Handles" (1) afaik, it's tied to the reference, not the
object, so if the reference changes to point to another object, it
automatically handles removing the handler from the old object and
adding it to the new object. (2) Since declaration and handling are all
in one line (the function declaration) you can just delete the
declaration when you accidentally create new handler code after
accidentally doubleclicking on a widget, rather than having to crawl
into the autogenerated code to find that += statement.

Martijn Mulder wrote:
There are 2 ways to hook an event to a method. For example, to hook the
MouseEnter-event, you can use

MouseEnter+=OnM ouseEnter;

or

MouseEnter+=new System.EventHan dler(OnMouseHan dler);

Both work well, as demonstrated by the small program below, where the
MouseEnter-event is hooked the one way, the MouseLeave-event the other. What
is the preferred way to hook events to methods, and why?
//class Formclass Form:System.Win dows.Forms.Form { //data member label
System.Windows. Forms.Label label=new System.Windows. Forms.Label();
//constructor Form() { Controls.Add(la bel); MouseEnter+=OnM ouseEnter;
MouseLeave+=new System.EventHan dler(OnMouseLea ve); } //OnMouseEnter void
OnMouseEnter(Sy stem.Object a,System.EventA rgs b) {
label.Text="Mou seEntered"; } //OnMouseLeave void OnMouseLeave(Sy stem.Object
a,System.EventA rgs b) { label.Text="Mou seLeft"; } //Main [System.STAThrea d]
static void Main() { System.Windows. Forms.Applicati on.Run(new Form()); }}
Nov 21 '06 #7
Advantages of "Handles" ..SNIP..

Disadvantage of "Handles":

If you want your event handlers to activate *after* you set all your
design time values, so they don't fire while initializing, you still
have to use the syntax where you "add" the function to the event.

Not a very big problem for us C# programmers, but as I have experienced,
it tends to confuse VB programmers to no end.

The C# Forms Designer, by the way (as you probably all know), always
adds the handler to the event *after* design time property
initialization of its controls. Default behavior in that respect differs
from the VB way using "Handles". I personally definitely prefer the C# way.

David
Nov 21 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
2294
by: Jeffrey T. Smith | last post by:
Back when the new J2SE1.5 features were announced, there was a JavaLive community chat (http://java.sun.com/developer/community/chat/JavaLive/2003/jl0729.html) in which Neal Gafter explains the Sun stance on lack of support for delegates: .... There are serious semantic problems with trying to add delegates to a language in a consistent way. The main problem is that once you call the delegate, the original class instance is no longer...
3
397
by: Sam | last post by:
I’m just starting to learn delegates. I’m at the very beginning. If I understand correctly, delegates are for when you want to pass a function as a parameter. For example the client provides a custom function to be called in a provider class. My confusion is that you can already achieve this by interfaces and objects without delegates (which have a little more complicated syntax) Here is an example without delegates. class Class1 and...
4
22894
by: LP | last post by:
Hello! I am still transitioning from VB.NET to C#. I undertand the basic concepts of Delegates, more so of Events and somewhat understand AsyncCallback methods. But I need some clarification on when to use one over another? If anyone could provide any additional info, your comments, best practices, any good articles, specific examples, etc. Thank you
4
1880
by: AMDRIT | last post by:
I am trying to understand Delegates and where/when to use them. I can see one potential use of a delegate (on form closing, set the cancel property in the event arguments.) Does anyone have a link to a site that describes delegates using VB.Net in a manner that doesn't require rocket science to become enlightened. TIA
6
2638
by: =?Utf-8?B?Sko=?= | last post by:
I have a logger component that logs to multiple sources, ie textfile, eventlog etc. and I have two methods that depending on where I call up my logger comp. one of them will be called. For ex. if I throw an exception I want to call one method and if I dont, I am just logging some info to eventlog, I will call the other. Now i'm wondering would it make sense to use delegates, one for each method to call methods in my window service? How...
0
4777
by: bharathreddy | last post by:
Delegates Here in this article I will explain about delegates in brief. Some important points about delegates. This article is meant to only those who already know delegates, it will be a quick review not a detailed one. Delegates quite simply are special type of object, a delegate just contains the details of a method. One good way to understanding delegates is by thinking of delegates as something that gives a name to a method...
6
2664
by: =?Utf-8?B?T2xkQ2FEb2c=?= | last post by:
My question is regarding the use of delegates in C#. I see how .Net uses delegates to wire event handlers to events. It’s an object created by a single line of code by the system and that makes perfect sense to me. I understand that there is a lot of code underneath that the system has created that makes it all work, thereby making it pretty efficient for the programmer. Outside of the use of delegates to wire event handlers, you can...
7
3425
by: Siegfried Heintze | last post by:
I'm studying the book "Microsoft Visual Basic.NET Language Reference" and I would like some clarify the difference between events and delegates. On page 156 I see a WinForms example of timer that uses the "WithEvents" and events. There is another example on page 124 that shows how to use delegates to sort an array. I don't understand the difference between events and delegates. Are they redundant features? How do I decide which to use? ...
69
5599
by: raylopez99 | last post by:
They usually don't teach you in most textbooks I've seen that delegates can be used to call class methods from classes that are 'unaware' of the delegate, so long as the class has the same signature for the method (i.e., as below, int Square (int)). Here is an example to show that feature. Note class "UnAwareClass" has its methods Square and Cuber called by a class DelegateClass. This is because these methods in UnAwareClass have the...
9
3120
by: raylopez99 | last post by:
Hello all— I’m trying to get the below to work and cannot get the format right. It’s from this example: http://msdn.microsoft.com/en-us/library/8627sbea(VS.71).aspx What it is: I’m trying to store multicast delegates in a hash table, and then fire the delegates one of two ways (after registering/ creating the delegates, etc).
0
9795
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10781
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10541
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10212
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9320
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7753
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5789
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4421
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3972
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.