C# Noob - Why check for null when raising event?

  • Thread starter Thread starter Richard Coltrane
  • Start date Start date
R

Richard Coltrane

Hi there,

Im stepping into C# from VB.net. In all the examples ive seen about raising
events the following construct is used:

if (myevent != null)
myevent(this,args);

Whats the purpose of the test for null? Is that testing to see if the
underlying delegate is null? If so when would it be?

TIA

Richard
 
Richard,

The underlying delegate will be null if no event handlers are assigned
to it, hence the need for the check.

Hope this helps.
 
Richard said:
Hi there,

Im stepping into C# from VB.net. In all the examples ive seen about raising
events the following construct is used:

if (myevent != null)
myevent(this,args);

Whats the purpose of the test for null? Is that testing to see if the
underlying delegate is null? If so when would it be?

TIA

Richard

Hi Richard,

When you define an event:

public event EventHandler MyEvent;

it doesn't have any handlers associated with it so MyEvent == null;
until you register an event handler(s) with the event:

SomeObj.MyEvent += new EventHandler(MyHandler);

That's why you need to check for null every time you want to fire the event.

Let me know if you need any further information.

Hope it helped,
Andrey
 
If you're wondering why it's not required in VB, it's because VB
automatically does the null check when you use RaiseEvent.
--
David Anton
www.tangiblesoftwaresolutions.com
Instant C#: VB to C# converter
Instant VB: C# to VB converter
Instant C++: C#/VB to C++ converter
Instant Python: C#/VB to Python converter
 
Thanks all.

Ive been using C# for about 3 days and im already beginning to appreciate
just how much cotton wool VB.Net wraps us in. :)
That's not neccessarily a bad thing but it is very noticable.

Once i can get out of the habit of "As"ing my method params and "Then"ing my
"If"'s, I think im really going to like this C# business.

Im also quite pleased about how easy it is to transfer concepts across the
platform. Syntax is different but the BCL sure is a great common
denominator.

Still not convinced about those blimmin' braces { } but i guess I shouldn't
expect a totally painless transition to the "dark side".

;)

Thanks
Richard
 
Back
Top