Home >Backend Development >C++ >How to Resolve the C# CS0120 Error: 'An Object Reference Is Required for the Nonstatic Field, Method, or Property'?
This error arises when you try to access a non-static member (field, method, or property) from within a static context, such as a static method or a static property.
Scenario:
Imagine this code:
<code class="language-csharp">public partial class MyForm : Form { private void MyMethod(object sender, EventArgs e) { // Error: Accessing a non-static member from a static method UpdateLabel(someValue); } private void UpdateLabel(string text) { myLabel.Text = text; // myLabel is a non-static member (control) } }</code>
Solutions:
Several approaches can resolve this:
Make the Member Static: If appropriate, change the member being accessed to static
. This works only if the member doesn't rely on instance-specific data.
<code class="language-csharp">public static void UpdateLabel(string text) // Now static { // Access static members only here! You can't access myLabel directly. }</code>
Singleton Pattern: Use a singleton to access the instance of your class. This is suitable when you need only one instance of the class.
<code class="language-csharp">public partial class MyForm : Form { private static MyForm _instance; // Singleton instance public static MyForm Instance { get { return _instance ?? (_instance = new MyForm()); } } private MyForm() { } // Private constructor private void MyMethod(object sender, EventArgs e) { Instance.UpdateLabel(someValue); } // UpdateLabel remains non-static }</code>
Instantiate the Class: Create an instance of the class within the static method.
<code class="language-csharp">private static void MyMethod(object sender, EventArgs e) { var form = new MyForm(); form.UpdateLabel(someValue); }</code>
Make the Calling Method Non-Static: The simplest solution is often to make the method calling the non-static member non-static.
<code class="language-csharp">private void MyMethod(object sender, EventArgs e) // Remains non-static { UpdateLabel(someValue); }</code>
Further Reading:
The above is the detailed content of How to Resolve the C# CS0120 Error: 'An Object Reference Is Required for the Nonstatic Field, Method, or Property'?. For more information, please follow other related articles on the PHP Chinese website!