473,721 Members | 1,825 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

A question about Events in C#

Hi

I have a question about events in C#.

In C#, we declare an event like this.

public delegate void EventHandlerA()
public class A
{
public event EventHandlerA eventObject = null;

private void SomeMethod()
{
if (eventObject != null)
{
eventObject();
}
}
}

class ClientOfClassA
{
ClassA objClassA = new ClassA();
objClassA.event Object += new EventHandlerA(s omeFunctionOfCl ient)
}

My questiion is
When the user created an instance of classA, the classA.eventObj ect is
set to null. Immidiately after that the user hooks to the event by
executing += operator. If the object is null, why an exception is NOT
thrown when we execute += operator on a null object.

Best regards
Amit

Dec 28 '05 #1
3 1181
Because in this case += doesn't really mean "add a value to"... it
means "add a new event handler to". The only reason I can imagine why
the C# decided to make a delegate with no client handlers "null"
instead of an empty list of event handlers is to save a little bit of
memory for events that have no subscribers. That little bit of memory,
over and over again (and the code to initialize it) probably saves
quite a bit in a good-sized program.

So, in the end, it's just a convention. Somewhere under the covers the
compiler (or the CLR) knows that when you say += for an event that has
the value null, it means to allocate a list for handlers and add the
given handler, just as when you say -= to remove the last event handler
from an event, the compiler (or the CLR) knows to remove the last
handler and set the event delegate to null.

Dec 28 '05 #2
Amit <am********@yah oo.com> wrote:
I have a question about events in C#.

In C#, we declare an event like this.

public delegate void EventHandlerA()
public class A
{
public event EventHandlerA eventObject = null;

private void SomeMethod()
{
if (eventObject != null)
{
eventObject();
}
}
}
Well, you may do - I don't (in any code which needs to be threadsafe).

See http://www.pobox.com/~skeet/csharp/t...ckchoice.shtml
class ClientOfClassA
{
ClassA objClassA = new ClassA();
objClassA.event Object += new EventHandlerA(s omeFunctionOfCl ient)
}

My questiion is
When the user created an instance of classA, the classA.eventObj ect is
set to null. Immidiately after that the user hooks to the event by
executing += operator. If the object is null, why an exception is NOT
thrown when we execute += operator on a null object.


Because the auto-generated "add" code (which is actually invoked when
you use += on an event) uses Delegate.Combin e, which is a static method
which can take null parameters.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Dec 28 '05 #3
Bruce Wood <br*******@cana da.com> wrote:
Because in this case += doesn't really mean "add a value to"... it
means "add a new event handler to". The only reason I can imagine why
the C# decided to make a delegate with no client handlers "null"
instead of an empty list of event handlers is to save a little bit of
memory for events that have no subscribers. That little bit of memory,
over and over again (and the code to initialize it) probably saves
quite a bit in a good-sized program.


It's not really C#, it's the CLR. I can see why they did this -
consider default construction of an instance of a type. It's usually
just a case of setting all bits to zero, then running a constructor. It
would be a pain (in many places, I suspect) if you had to ensure that
you *always* ran an extra bit of code to change the value of delegate
fields was initialized to a non-null value. It's certainly a pain in
the neck though. Of course, if you're using your own event add/remove
code, you can always set the initial value of the event delegate
yourself.

<snip>

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Dec 28 '05 #4

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

Similar topics

220
19078
by: Brandon J. Van Every | last post by:
What's better about Ruby than Python? I'm sure there's something. What is it? This is not a troll. I'm language shopping and I want people's answers. I don't know beans about Ruby or have any preconceived ideas about it. I have noticed, however, that every programmer I talk to who's aware of Python is also talking about Ruby. So it seems that Ruby has the potential to compete with and displace Python. I'm curious on what basis it...
1
3045
by: Steve | last post by:
I've run in to a problem with a query I'm trying to write. I have attached a sample SQL script at the end of this post to show an overview of what I'm working with. I want to be able to use LIMIT to control how many rows from one table are returned, independent of how many rows there are in a second table that is joined to the first. When I execute the following SQL script:
20
3340
by: Olav.NET | last post by:
I am a .NET/C++ developer who is supposed to do some work with Access. I do not know much about it except for the DB part. Questions: *1* I am looking for INTENSIVE books to get quickly up to speed. I like books with practical exercises, and also with test questions (like cert books) *2*
4
1280
by: news.microsoft.com | last post by:
In one of my books called "Mastering C#" there is a statement that reads "All event handler delegates must return void and accept two parameters. The first parameter is an object, and it represents the object that raises the event... The second is a parameter that is an object of a class derived from the System.EventArgs class". Now I know that this can not be true in general because I have created events that do not match these...
1
1157
by: Christoph Boget | last post by:
Where can I find *comprehensive* information about events? I've been all through Microsofts developer pages, through the VS.NET help but I can't find comprehensive, details information about them. For example, I'm working with a TreeView control. I've set up 2 even handler methods, one for "AfterSelect" and one for "Click". In the "AfterSelect" handler method, I can access the TreeView object to get state information and work with member...
6
1345
by: Flare | last post by:
Hi i have a qusstion about events and delegates. Especially the precis role of the Event. Eg. We have a class wich want to fire events so we declare: public delegate void TestEventHandler(object sender, EventArgs arg); public event TestEventHandler Test; And fire the event with
1
1360
by: e-mid | last post by:
i registered two events with a button. when i press it , how can i know which is fired first? or is there a way to make one of them get fired before the other one? in fact i made a experiment about it : i put message boxes in the events, when i press button only one event is fired and other is never. why does that happens?
1
1133
by: Tom Rahav | last post by:
Hi, I use VB .NET 2003 and I want to create a new UserControl that will function as a "smart" combobox that handles few events automatically (such as auto-complete, etc.) in addition to the regular combobox events. I created a new class that inherits from: System.Windows.Forms.ComboBox. I added the some code to the events in the new combobox (in the UserControl project) and add the control to a win-form in a different project. The...
8
4271
by: Tony Johansson | last post by:
Hello! I wonder can somebody explain when is it suitable to use these methods OnKeyUp, OnKeyDown and OnKeyPress because these raise an event. These are located in class UserControl. If these raise an event how do I create an handler to catch these raised events. //Tony
1
4905
by: swethak | last post by:
Hi, I am desiging the calendar application for that purpose i used the below code. But it is for only displys calendar. And also i want to add the events to calendar. In that code displys the events when click on that date that perticular event displyed in a text box.But my requirement is to when click on that date that related event displyed in same td row not the text box. and also i add the events to that calendar.plz advice how to...
0
8844
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
8731
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9218
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9132
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
8009
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
6672
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
4755
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3191
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
2578
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.