Search code examples
c#wpfobject-reference

Error: “an object reference is required for the non-static field, method or property…”


I have a WPF client programmed with c#. The program is a register demo, you type a name and say if they are here or not and send it to a server and port that is entered into a textbox by the user.

When trying to apply this in the code however, I get the error: “an object reference is required for the non-static field, method or property…”. This is on the "client.connect" line...

namespace client
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        public MainWindow()
        {
            InitializeComponent();
        }

        public class connectandsend
        {

            //if 'REGISTER' button clicked do this...{
            static void connect()
            {
                TcpClient client = new TcpClient(); // New instance of TcpClient class of the .Net.Sockets
                client.Connect(server_txt.Text, Convert.ToInt32(port_txt.Text)); // Server, Port
                StreamWriter sw = new StreamWriter(client.GetStream()); // New StreamWriter instance
                StreamReader sr = new StreamReader(client.GetStream()); // New StreamReader instance
            }

            /* static void send()
            {
                stream write... name.text and 'here' or 'not here' ticked box?
            }

            }
            */
        }

    }
}

Solution

  • The connect() method cannot be static if you want to be able to access any non-static members of the MainWindow in it. Also it cannot be located in another class unless this class or the method itself also has a reference to the MainWindow class.

    Remove the static keyword and move the method to the MainWindow class:

    public partial class MainWindow : Window
    {
    
        public MainWindow()
        {
            InitializeComponent();
        }
    
        void connect()
        {
            ...
        }
    }
    

    Or pass the server_txt.Text and port_txt.Text to the method when you call it:

    static void connect(string server, int port)
    {
        TcpClient client = new TcpClient(); // New instance of TcpClient class of the .Net.Sockets
        client.Connect(server, port); // Server, Port
        StreamWriter sw = new StreamWriter(client.GetStream()); // New StreamWriter instance
        StreamReader sr = new StreamReader(client.GetStream()); // New StreamReader instance
    }
    

    MainWindow:

    connectandsend.connect(server_txt.Text, Convert.ToInt32(port_txt.Text));