Object reference not set to an instance of an obje

2019-09-21 11:34发布

问题:

This question already has an answer here:

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

I'm getting an error message and I don't know how to fix it. This is the original code I have:

private void SendMessage(Command cmd, EndPoint sendToEP)
{
    try
    {
        //Create the message to send.
        Data msgToSend = new Data();

        //msgToSend.strName = txtName.Text;   //Name of the user.
        msgToSend.cmdCommand = cmd;         //Message to send.
        msgToSend.vocoder = vocoder;        //Vocoder to be used.

        byte[] message = msgToSend.ToByte();

        //Send the message asynchronously.
        clientSocket.BeginSendTo(message, 0, message.Length, SocketFlags.None, sendToEP, new AsyncCallback(OnSend), null);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "UniProject-SendMessage ()", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

The error message is (button press event)

Object reference not set to an instance of an object.

Why am I getting this error message and how can i fix it?

回答1:

Every time you get such an error (a NullReferenceException), there is something in your code that is set to null. You have to look at your code and determine:

  1. On which line (in which method) does the error occur?
  2. What variables on that line are reference types or nullable value types?
    Normal value types (e.g. struct, or integers, floats, doubles) cannot be null.
  3. Of those variables, which could possibly be null?
  4. Where are those variables possibly set to null?
    For example, a method argument, a value returned from a method, or the result of the as operator can result in a variable being null.

If none of those is the case, you might have (although unlikely) a method that is throwing this exception. The .NET base class methods generally don't throw such an exception, and if your code does throw it, your stack trace should bring you to the deepest method and line that does that.



标签: c# winsockets