Меню

Ошибка an object reference is required for the non static field method or property

  • Remove From My Forums
  • Question

  • This is likely another stupid newbie question but I need to understand this. I created a project and added a class to it. When i tried to access any of the global members of the class I would get the compiler message listed in the subject. Without thinking about it to much I put static qualifiers on all the members and went merrily along my way. Then I got to thinking about it and it didnt make sense to me. A member of a class whether it be a method an object or a primitive should be accessible to all methods in the class.

    Looking at other projects Ive done in c# this seems to be the case.  This was the first time though that I added a new class from scratch to a project and Im now wondering what I did wrong.

    Here is a very basic code sample of the class I created. If it makes any difference this class is used for the thread thats doing all the work in a Windows Service. The OnStartup method of LLScan creates the thread.


    namespace LLScan

    {

    public class LLSCanJob

    {

    private static System.DateTime scanDate;


    private static string strDate = «»;


    private static string logfileName = «»;


    private static System.IO.FileStream logFile;


    private static System.IO.StreamWriter sw;


    public static void threadProcess()

    {

    //Debugger.Launch();

    openLogFile();

    getScanTarget();

    try

    {

    while (true)

    {

    // check if we have work to do.


    System.DateTime dt = System.DateTime.Now;


    if (dt > scanDate)

    {

    }

    Thread.Sleep(30000); // Check if we need to wake up every 30 seconds.

    }

    }

    catch

    {

    }

    finally

    {

    // This code will be hit for sure when the Thread.Abort method is executed.

    sw.Flush();

    sw.Close();

    }

    }

    Anyone care to enlighten this confused newbie ?

Answers

  • If you have a variable in a class which is just declared «private», an instance of that variable is only created when an instance of the class is created. For example:

    public class Person
    {
      private string name;

      public void PrintName()
      {
        Console.WriteLine(name);
      }
    }

    Person person1 = new Person();
    Person person2 = new Person();

    Now person1 has a string variable called name, and person2 has a different instance.

    The PrintName method is also bound to the instance of the class with which it is called, so if you call person1.PrintName(), it will output person1.Name, and if you call person2.PrintName(), it will output person2.name.

    A static method, on the other hand, is not bound to any instance of the class; it exists within the class itself. The class doesn’t have an instance of the «name» variable because it wasn’t declared static. So the static method needs to be given an instance of the class to work against, e.g.:

    public class Person
    {
      …
      public static void PrintName(Person person)
      {
        Console.WriteLine(person.name);
      }
    }

    I don’t know if I’ve explained that very well.

The C# “an object reference is required for the non-static field” error is thrown when an object reference is required for the nonstatic field, method or property..

Install the C# SDK to identify and fix these errors

Introduction to an Object Reference is required for the non-static field

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

In order to use a non-static field, method, or property, you must first create an object instance.

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?

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

In this tutorial, you’ll learn everything about the error “CS0120 – An object reference is required for the nonstatic field, method, or property ‘member’ in C#, why this error appears in your .NET Code and how you can fix them in simple steps.

C# Compiler Error

This is how the CS0120 error in C# looks like in general.

CS0120 – An object reference is required for the nonstatic field, method, or property ‘member’

Reason for the Error

You will receive the CS0120 error in C# when you are trying to access an non-static field, property or method from a static class.

For example, the below code snippet contains a non-static property MyProperty defined in the class by name “DeveloperPublish” and you are trying to access this non-static property from a static method (“Main”) defined in the same class.

namespace DeveloperPublishNamespace
{

    public class DeveloperPublish
    {
        public int MyProperty { get; set; }
        public static void Main()
        {
            MyProperty = 1;
        }
    }
}

This will result with the compiler error CS0120.

Error CS0120 An object reference is required for the non-static field, method, or property ‘DeveloperPublish.MyProperty’ ConsoleApp1 C:UsersSenthilsourcereposConsoleApp1ConsoleApp1Program.cs 9 Active

C# Error CS0120 – An object reference is required for the nonstatic field, method, or property 'member'

Solution

To fix the CS0120 Error in C#, avoid accessing the non-static member directly from the static method.

See more:

i learn c++ and i begin learn c#, i dont understand method
help me error
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace text1
{
    class Program
    {
        public int pt(int l, int r)
        {
            return l + r;
        }
        static void Main(string[] args)
        {
            float i;
            var c = 10;
            Console.WriteLine("Hello World");
            Console.ReadLine();
            for (i = 1; i <= 10; i++)
                {   Console.WriteLine("Hello World");
                    Console.WriteLine(c);
                    
                };
            string a, b;
            a = "vu anh";
            b = "dep trai";
            Console.WriteLine(a + " " + b);
            int j;
            j = pt(3, 4);
            Console.WriteLine(i);
            Console.Beep();
            Console.ReadLine();
        }
    }
}

i get error "An object reference is required for the non-static field, method, or property 'text1.Program.method(int, int)'"
thank

Comments


Solution 3

An alternative to requiring that you create an instance of Program is that you make pt() itself a static method. Since pt() only operates on its parameters (i.e. it doesn’t reference any instance members of its defining type) making it static is an appropriate choice.

Solution 1

Since Main is static, you cannot use the rest of the Program Class inside your static method.

Therefore you need an instance of the Program Class.
Change

int j;        
j = pt(3, 4);

Into

int j;
Program P = new Program();
j = P.pt(3, 4);

I would recommend writing the pt(int,int) method in another class though, but maybe thats just me.

Solution 2

Hi,

you are calling an instance method pt() from a static method (Main). To correct this error, either (i) declare a variable of type program and then call the method or (2) add ‘static’ to the declaration of method pt().

// option 1
int j;
Program program = new Program(); // new line
j = program.pt(3, 4);            // replace this line "j = pt(3, 4);"

// option 2
public static int pt(int l, int r)
{
    return l + r;
}

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

 

Print

Answers RSS

Top Experts
Last 24hrs This month

CodeProject,
20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8
+1 (416) 849-8900

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка api фн функция closefiscmodecommit
  • Ошибка asr мерседес 140