Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top