Blog |

How to Resolve an object reference is required for the non-static field

How to Resolve an object reference is required for the non-static field
Table of Contents

The "Object reference is required for the non-static field" error happens in C# when you try to access a non-static member from a static method.

Every class in C# can have two types of members: static and non-static. Static members are shared by the whole class, like a public bulletin board anyone can read. Non-static members are different - they belong to specific instances of the class, like personal notes that only exist in your copy of a notebook. This error occurs when a static method tries to use a non-static member without having an instance to work with.

Let's look at some code where this happens - we'll see how trying to update a form label from a static method causes this error, and show you three simple fixes.

Consider the following C# example

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 happening?

An object reference is required for the nonstatic
field, method, or property

'WindowsApplication1.Form1.setTextboxText(int)

Calling a non-static member (a property or method, specifically setTextboxText) from a static method (specifically SumData) is causing this error.

How to fix "object reference is required for the non-static field"

Here are three different ways to fix this error. Choose the approach that works best for your situation:

1. Make the called member static also:

static void setTextboxText(int result)
{
    // Write static logic for setTextboxText.  
    // This may require a static singleton instance of Form1.
}

2. Create an instance of Form1 within the calling method:

private static void SumData(object state)
{
    int result = 0;
    //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);
}

Passing in an instance of Form1 would be an option also.

3. Make the calling method a non-static instance method (of Form1):

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

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

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing C# errors easier than ever. Sign Up Today!

References

[1] StackOverFlow, 2021. Online: https://stackoverflow.com/questions/498400/cs0120-an-object-reference-is-required-for-the-nonstatic-field-method-or-prop

Related Resources

"Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind."

Error Monitoring

Start continuously improving your code today.

Get Started Shape