Home >Backend Development >C++ >Why Does 'CS0120: An object reference is required...' Occur When Calling a Non-Static Method from a Static Method?

Why Does 'CS0120: An object reference is required...' Occur When Calling a Non-Static Method from a Static Method?

DDD
DDDOriginal
2025-02-02 17:51:11704browse

Why Does

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

Scenario:

Consider the following code:

private static void SumData(object state)
{
    // Calling a non-static member from a static method
    setTextboxText(result);
}

Explanation:

The error "CS0120" occurs when you attempt to access a non-static member (field, method, or property) from a static context. In this case, the setTextboxText method is a non-static member of the Form1 class, and it cannot be accessed from the static SumData method.

Possible Solutions:

  • Make the Non-Static Member Static:
static void setTextboxText(int result)
{
    // Implementation details
}
  • Use a Static Singleton of Form1:
class Form1
{
    public static Form1 It;

    public Form1()
    {
        It = this;
    }

    private static void SumData(object state)
    {
        Form1.It.setTextboxText(result);
    }
}
  • Pass an Instance of Form1 to the Calling Method:
private static void SumData(Form1 form, object state)
{
    form.setTextboxText(result);
}
  • Make the Calling Method Non-Static:
private void SumData(object state)
{
    setTextboxText(result);
}

Additional Information:

  • Static members can only access other static members.
  • Non-static members can access both static and non-static members.
  • If an instance of the class is not available during the call to a non-static member, you can create a new instance or use static singletons to access the non-static member.
  • Refer to MSDN for more information about this error.

The above is the detailed content of Why Does 'CS0120: An object reference is required...' Occur When Calling a Non-Static Method from a Static Method?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn