CS0120: An object reference is required for the nonstatic field, method, or property 'foo'

c#

Question

Consider:

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //int[] val = { 0, 0};
            int val;
            if (textBox1.Text == "")
            {
                MessageBox.Show("Input any no");
            }
            else
            {
                val = Convert.ToInt32(textBox1.Text);
                Thread ot1 = new Thread(new ParameterizedThreadStart(SumData));
                ot1.Start(val);
            }
        }

        private static void ReadData(object state)
        {
            System.Windows.Forms.Application.Run();
        }

        void setTextboxText(int result)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new IntDelegate(SetTextboxTextSafe), new object[] { result });
            }
            else
            {
                SetTextboxTextSafe(result);
            }
        }

        void SetTextboxTextSafe(int result)
        {
            label1.Text = result.ToString();
        }

        private static void SumData(object state)
        {
            int result;
            //int[] icount = (int[])state;
            int icount = (int)state;

            for (int i = icount; i > 0; i--)
            {
                result += i;
                System.Threading.Thread.Sleep(1000);
            }
            setTextboxText(result);
        }

        delegate void IntDelegate(int result);

        private void button2_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
    }
}

Why is this error occurring?

An object reference is required for the nonstatic field, method, or property 'WindowsApplication1.Form1.setTextboxText(int)

1
222
6/12/2019 5:00:03 AM

Accepted Answer

It looks like you are calling a non static property from a static method. You will need to either make the property static, or create an instance of Form1.

static void SetTextboxTextSafe(int result)
{
    label1.Text = result.ToString();
}

OR

private static void SumData(object state)
{
    int result;
    //int[] icount = (int[])state;
    int icount = (int)state;

    for (int i = icount; i > 0; i--)
    {
        result += i;
        System.Threading.Thread.Sleep(1000);
    }
    Form1 frm1 = new Form1();
    frm1.setTextboxText(result);
}

More info about this error can be found on MSDN.

334
12/21/2017 7:02:22 PM

You start a thread which runs the static method SumData. However, SumData calls SetTextboxText which isn't static. Thus you need an instance of your form to call SetTextboxText.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon