473,698 Members | 2,048 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

When is an event null?

Suppose I have this:

class C {
public delegate void MyEventHandler( );
public event MyEventHandler MyEvent;

public void foo() {
MyEvent(); // NullReferenceEx ception?
}
}

Under what circumstances will trying to raise the event in the foo
method generate a NullReferenceEx ception, and why?

Nov 16 '06 #1
22 16930
dv*****@gmail.c om wrote:
Suppose I have this:

class C {
public delegate void MyEventHandler( );
public event MyEventHandler MyEvent;

public void foo() {
MyEvent(); // NullReferenceEx ception?
}
}

Under what circumstances will trying to raise the event in the foo
method generate a NullReferenceEx ception, and why?
You'll get a NullReferenceEx ception if no-one has subscribed to the
event.
By declaring a "field-like event" you get an event (which is basically
an add/remove pair) and a field of the delegate type. The field's value
is null if no-one has subscribed to it.

See http://www.pobox.com/~skeet/csharp/events.html for a rather fuller
description.

Jon

Nov 16 '06 #2
You always need to check
If(MyEvent != null)

Because an event is null when no one is subscribed.

Regards,

Bela Istok
<dv*****@gmail. comwrote in message
news:11******** **************@ m7g2000cwm.goog legroups.com...
Suppose I have this:

class C {
public delegate void MyEventHandler( );
public event MyEventHandler MyEvent;

public void foo() {
MyEvent(); // NullReferenceEx ception?
}
}

Under what circumstances will trying to raise the event in the foo
method generate a NullReferenceEx ception, and why?

Nov 16 '06 #3
Suppose I have this:
>
class C {
public delegate void MyEventHandler( );
public event MyEventHandler MyEvent;
public void foo() {
MyEvent(); // NullReferenceEx ception?
}
}
Under what circumstances will trying to raise the event in the foo
method generate a NullReferenceEx ception, and why?
The event will be null until an event handler is actually added to it. And,
it will be null after the last event handler is removed from it. The reason
is that the code that you posted really compiles to something that looks
a little more like this:

class C {
{
public delegate void MyEventHandler( );
private MyEventHandler _MyEvent;
public void add_MyEvent(MyE ventHandler value)
{
_MyEvent = (MyEventHandler )Delegate.Combi ne(_MyEvent, value);
}
public void remove_MyEvent( MyEventHandler value)
{
_MyEvent = (MyEventHandler )Delegate.Remov e(_MyEvent, value);
}
public void foo() {
MyEvent();
}
}

An event compiles to a private field that holds your delegate instance and
two methods that add and remove handlers to and from the delegate. When the
class is created, the field is null. When a handler is added to the event,
Delegate.Combin e() is called and that creates your delegate or adds the handler
to your delegate if it is already created. When a handler is removed from
the event, Delegate.Remove () is called and that removes the handler from
your delegate sets it to null if there aren't anymore handlers.

Best Regards,
Dustin Campbell
Developer Express Inc.
Nov 16 '06 #4
Bela Istok wrote:
You always need to check
If(MyEvent != null)

Because an event is null when no one is subscribed.
You certainly need to do the check, but in a multi-threaded environment
that's not enough.
See http://www.pobox.com/~skeet/csharp/lockchoice.shtml for more on
this.

(In environments where only single-threaded subscribe/unsubscribe/raise
are supported, the above is okay.)

Jon

Nov 16 '06 #5
JR
It probably should have been

http://www.yoda.arachsys.com/csharp/...ckchoice.shtml

JR

"Jon Skeet [C# MVP]" <sk***@pobox.co mwrote in message
news:11******** **************@ h54g2000cwb.goo glegroups.com.. .
Bela Istok wrote:
>You always need to check
If(MyEvent != null)

Because an event is null when no one is subscribed.

You certainly need to do the check, but in a multi-threaded environment
that's not enough.
See http://www.pobox.com/~skeet/csharp/lockchoice.shtml for more on
this.

(In environments where only single-threaded subscribe/unsubscribe/raise
are supported, the above is okay.)

Jon

Nov 16 '06 #6
Skeet, your link 404s. I can see why this would be confusing though -
the event has collection-like semantics, and one imagines that calling
the event would involve simply iterating across the list and calling
the handlers... so one would expect the empty event-handler-list would
simply be handled by iterating across an empty list - not by returning
a null complaint. I guess one could just wrap it in a generic
"CallEvent" function or something that does the null-check for you.

Jon Skeet [C# MVP] wrote:
Bela Istok wrote:
You always need to check
If(MyEvent != null)

Because an event is null when no one is subscribed.

You certainly need to do the check, but in a multi-threaded environment
that's not enough.
See http://www.pobox.com/~skeet/csharp/lockchoice.shtml for more on
this.

(In environments where only single-threaded subscribe/unsubscribe/raise
are supported, the above is okay.)

Jon
Nov 16 '06 #7
Jon,

First thanks for the link.

Second a question about you suggested method of implementing an event.

If "handler = someEvent", is not "handler" a reference to "someEvent" so
when "someEvent" loses the event handler would not "handler" also lose the
event handler?

Regards,
John

"Jon Skeet [C# MVP]" <sk***@pobox.co mwrote in message
news:11******** **************@ h54g2000cwb.goo glegroups.com.. .
Bela Istok wrote:
>You always need to check
If(MyEvent != null)

Because an event is null when no one is subscribed.

You certainly need to do the check, but in a multi-threaded environment
that's not enough.
See http://www.pobox.com/~skeet/csharp/lockchoice.shtml for more on
this.

(In environments where only single-threaded subscribe/unsubscribe/raise
are supported, the above is okay.)

Jon

Nov 16 '06 #8
Martin Z <ma***********@ gmail.comwrote:
Skeet, your link 404s.
Yup, sorry about that - as JR pointed out, the link should be

http://www.yoda.arachsys.com/csharp/...ckchoice.shtml
I can see why this would be confusing though -
the event has collection-like semantics, and one imagines that calling
the event would involve simply iterating across the list and calling
the handlers... so one would expect the empty event-handler-list would
simply be handled by iterating across an empty list - not by returning
a null complaint. I guess one could just wrap it in a generic
"CallEvent" function or something that does the null-check for you.
Well, it's consistent with a collection being null as well. I agree it
would be nice if delegates had an easy way of creating an "empty"
handler list, and indeed you can start off an event that way and avoid
the null check, but the default value of a field being null *is*
consistent with other semantics.

--
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
Nov 16 '06 #9
John J. Hughes II <no@invalid.com wrote:
First thanks for the link.

Second a question about you suggested method of implementing an event.

If "handler = someEvent", is not "handler" a reference to "someEvent" so
when "someEvent" loses the event handler would not "handler" also lose the
event handler?
No, "handler" and "someEvent" are both variables. After the assignment,
if "someEvent" changes to refer to a different delegate (or null) that
won't change the value of "handler".

Note that delegates are immutable - using += and -= doesn't change the
list of handlers within a specific delegate, it returns a *new*
delegate with a different list.

--
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
Nov 16 '06 #10

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

Similar topics

3
1754
by: Bruce Wood | last post by:
I need to remove all handlers from a particular event. I am doing this in the class where the event is defined. I have this vague memory that I can say: this.MyEvent = null; and this will clear all delegates from the event, but I'm not sure, and I can't find the relevant documentation.
1
1664
by: Amit Dedhia | last post by:
Hi I am developing an application using C++/CLI in Visual Studio 2005. In my application I have following structure. (1) Class A creates instances of Class B and Class C. (2) Class B implements a timer function which repeatedly executes a timer every 250 ms. (3) Class C instance hooks for a event raised by Class B instance. Class B always raises this event asynchronously at the end of timer
0
1443
by: Matt Michler | last post by:
I have a WebUserControl with a custom event, when this event is fired, the delegate or event object is throwing a null reference exception. The odd part of this is, it used to work flawlessly, now it never works. I'm not sure what change affected the event while my coworker and I were working on this control. Here's the event code in the control from which the event is spawned: <code> public Guid DbReferenceID { get {
6
1302
by: kirk | last post by:
I have three events, using event handler methods as depicted below. Two of those event handler methods need to reset specific data whenever the other event left fires. I wasn't sure how to properly implement that, is there a better way than using state management variables for each timer as i'm doing in the outline below? private string szProperty1 = null; // updated by class consumer
0
1075
by: kirk | last post by:
I have three events that I have created and manage with timers. Two of the timer event handlers, the last two in the code below, need to reset state management data, if the first event handler fires. My question, is what I have implemented the right way to design state management, or is there maybe a best practice to design this differently? private string szData1 = null; public string Data1 {
1
1221
by: anil kasar | last post by:
when event is occur then i want to show messagebox display on client side ?
0
9148
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...
0
9012
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
8884
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
8855
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...
1
6515
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
4358
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4611
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3034
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
2319
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.