Referencing "this" in event calls

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

Richard

When I reference "this" in call to event, I get the following error:

An unhandled exception of type 'System.NullReferenceException'
occurred in csbasesockets.dll

Additional information: Object reference not set to an instance of an
object.


Here is a summary of my code:

public delegate void TCPConnectionEventHandler(TCPConnection sender);

public class TCPConnection
{

public TCPConnection(){}

public event TCPCOnnectionEventHandler OnConnected;

public void Connect()
{
//some code to connect here...
this.OnConnected(this); <-- Error received here
}
}

public class frmClient: System.Windows.Forms.Form

{
public frmClient()
{
m_client = new TCPConnection();
m_client.OnConnected+= new
TCPConnectionEventHandler(this.client_OnConnected);
m_client.Connect();
}

private void client_OnConnected(TCPIPConnection sender)
{
//do something here...
}
}

When I hover over "this" there is information but when I hover over
"OnConnected" I can see "OnConnected = <undefined value>".

Thanks in advance...
 
Hi Richard,

OnConnected is an event and it doesn't have any delegates hooked up to it
yet. Here is how you should raise events:

if (OnConnected != null)
{
this.OnConnected(this);
}

Once a delegate is added to OnConnected, it will no longer evaluate to null.

Joe
 
Joe Mayo said:
OnConnected is an event and it doesn't have any delegates hooked up to it
yet. Here is how you should raise events:

if (OnConnected != null)
{
this.OnConnected(this);
}

Once a delegate is added to OnConnected, it will no longer evaluate to null.

It depends on how thread-safe you want things to be, however. I have a
section on making events thread-safe at
http://www.pobox.com/~skeet/csharp/multithreading.html#lock.choice
 
Jon Skeet said:
null.

It depends on how thread-safe you want things to be, however. I have a
section on making events thread-safe at
http://www.pobox.com/~skeet/csharp/multithreading.html#lock.choice

That's a pretty good article. What are your thoughts on the risk of someone
doing?:

someEvent = new SomeEventHandler(SomeMethod);

Since the someEvent delegate is private, I'm thinking the risk is minimal,
but am interested in what you think.

Joe
 
Joe Mayo said:
That's a pretty good article. What are your thoughts on the risk of someone
doing?:

someEvent = new SomeEventHandler(SomeMethod);

Since the someEvent delegate is private, I'm thinking the risk is minimal,
but am interested in what you think.

And doing that outside a lock? Yes, that would be dangerous just as any
unsynchronized access to shared data is dangerous. As you say though,
there's no danger *outside* the class.
 
Back
Top