0

There is a struct:

public struct ReturnedCommands
{
    public string   key;
    public string   command;
};

...and a variable:

public static ReturnedCommands returnedCommands; 

...and a Null Reference Exception occurring, returning the value "3":

public bool PendingCommandsExecute_QUERY()
{
    int i = 0;
    try
    {
        i = 1;
        cmdResults b = cmdResults.cmdFail;
        bool retVal = false;
        string command = "QUERY";

        if (returnedCommands.key != command) 
            return false;

        HashResultsAdd(command, "Started");
        i = 2;

        HashStatus.Clear();

        string sNum = PendingCommands.SiteFetchSiteNumber; 
        i = 3; // <-- last one reached (debug int displayed in NRE)
        string s = string.Empty;
        if (returnedCommands.command != null)
        {
            s =  command + "|" + sNum.Trim() + "|t_inv|SELECT|" + returnedCommands.command;
        }
        i = 4;
        HashStatusAdd(command, s);
        . . .
    } 
    catch( Exception ex )
    {
        MessageBox.Show(ex.Message + " reached debug int " + i.ToString());
    }
    return true;
} // PendingCommandsExecute_QUERY

When the NRE occurs, it shows "Exception: Null Reference Exception reached debug int 3". So, it must be imploding while referencing returnedCommands.command, but how could that be, as returnedCommands.command is simply a string? First verifying it's not null (the "if (returnedCommands.command != null)" line) should be safe, so that test should not be problematic; if it passes that test, it is just a string concatenation operation, so how could that be causing a NRE?

B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862

2 Answers2

5

if PendingCommands.SiteFetchSiteNumber is null (and thus sNum is null), then this would cause a null reference exception when you call sNum.Trim()

Also if you show the full stack trace it should give you the exact line number that the error occurred on, which is a lot simpler to debug than using an incremental value to figure it out.

Martin Ernst
  • 5,629
  • 2
  • 17
  • 14
  • The assignment "i = 3" is after that reference, so wouldn't the value of i in the exception be 2 in that case? – B. Clay Shannon-B. Crow Raven Jun 10 '13 at 16:32
  • No, the assignment i = 3 is after you assign sNum = PendingCommands.SiteFetchSiteNumber. This is valid to assign null to a variable, the problem comes in that a couple of lines later, you are trying to call a method (Trim) on a "null object" – Martin Ernst Jun 10 '13 at 16:37
1

It's most likely a missing check for multi thread access of the public static member.

public static ReturnedCommands returnedCommands;

I cannot see what you exactly want to achieve there, but I consider you reviewing the architecture, because it'll most likely fail when other threads have access to this member and overwrite it with null.

Probably you can use a queue for your commands.

Andre
  • 1,228
  • 11
  • 24