Access control from static method

jccorner

Centurion
Joined
Jan 31, 2004
Messages
144
I've been at this all afternoon and can't figure a way around it. The method has to be static so that is not an option of not being static. Here's the code:

Code:
 private static void ConnectionFilter(String sRemoteAddress, int nRemotePort, Socket sock)
        {
            lstMsg.Items.Add("Connection request from " + sRemoteAddress + ":" + nRemotePort.ToString());
        }

lstMsg is not available but I can't figure out why. I would greatly appreciate any assistance with this.
 
Static methods

Static methods can only access static class variables. If lstMsg is an instance (non-static) variable (as it would be by default) then it cannot be accessed from a static method. Static methods can be called even when no class instances exist, so cannot access class members without an explicit reference.

I assume this is part of a form's code, and that you expect only one instance of the form to be used. In that case you would need to store a reference to the form in a static variable, which static methods can access. For instance:

C#:
public partial class MyForm : Form
{
    private static MyForm m_theform;

    //Constructor
    public MyForm()
    {
        //Set m_theform to point to this
        MyForm.m_theform = this;
    }

    //Static method
    private static void ConnectionFilter(String sRemoteAddress, int nRemotePort, Socket sock)
    {
        MyForm.m_theform.lstMsg.Items.Add("Connection request from " + sRemoteAddress + ":" + nRemotePort.ToString());
    }
}

I notice that the method is private, so I assume you're calling it from another static method, otherwise it might as well be non-static.

Good luck :cool:
 
Back
Top