0

Why is the code below throwing the Object reference error when it tries to use the ClientSocket?

I copied this example from the Interactive Brokers API documentation.

https://www.interactivebrokers.com/en/software/api/api.htm

I am connected using the IB Gateway.

https://www.interactivebrokers.com/en/index.php?f=5041

I have seen the following post, but it is still not clear what I am doing wrong here.

What is a NullReferenceException, and how do I fix it?

Throws the error on the myClient.ClientSocket line:

var myClient = new EWrapperImpl();

myClient.ClientSocket.eConnect("127.0.0.1", 7496, 0);

Here is the wrapper class:

public class EWrapperImpl : EWrapper
{
    EClientSocket clientSocket;

    public EWrapperImpl()
    {
        clientSocket = new EClientSocket(this);
    }

    public EClientSocket ClientSocket { get; set; }
}
Community
  • 1
  • 1
ADH
  • 2,971
  • 6
  • 34
  • 53

1 Answers1

2

Please note that you initialize the private field clientSocket (with a lower-case 'c') in your constructor, but access a public field or property ClientSocket (with an upper-case 'C'). So, you are initializing a field that gets never used and try to access a property that is never initialized.

The easiest way to fix your code is to remove the private field and to initialize the property instead:

public class EWrapperImpl : EWrapper
{
    public EWrapperImpl()
    {
        ClientSocket = new EClientSocket(this);
    }

    public EClientSocket ClientSocket { get; set; }
}
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
  • Sorry, that line of code was omitted for brevity. I added it to the post. public EClientSocket ClientSocket { get; set; } – ADH Mar 09 '16 at 09:43
  • I think the real problem is that the program cannot tell that the IB Gateway is connected. But, I will try your edits. – ADH Mar 09 '16 at 09:59
  • That did fix the null reference error. Why would the documentation be so wrong? – ADH Mar 09 '16 at 10:03
  • @ADH: The documentation is correct. But you didn't copy that code exactly. Your property is an auto-property. Their property is using the private field. There is your error. – Daniel Hilgarth Mar 09 '16 at 10:16
  • Okay, I see it now. Thank you. – ADH Mar 09 '16 at 11:19