Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All
Expand Minimize
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.

Compiler Error CS0120 

Error Message

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. For more information, see Instance Constructors (C# Programming Guide).

The following sample generates CS0120:

// CS0120_1.cs
public class MyClass
{
   // Non-static field
   public int i; 
   // Non-static method
   public void f(){}
   // Non-static property
   int Prop
   {
      get 
      {
         return 1; 
      }
   }

   public static void Main()
   {
      i = 10;   // CS0120
      f();   // CS0120
      int p = Prop;   // CS0120
      // try the following lines instead
      // MyClass mc = new MyClass();
      // mc.i = 10;
      // mc.f();
      // int p = mc.Prop;
   }
}

CS0120 will also be generated if there is a call to a non-static method from a static method, as follows:

// CS0120_2.cs
// CS0120 expected
using System;

public class MyClass
{
   public static void Main()
   {
      TestCall();   // CS0120
      // To call a non-static method from Main,
      // first create an instance of the class.
      // Use the following two lines instead:
      // MyClass anInstanceofMyClass = new MyClass();
      // anInstanceofMyClass.TestCall();
   }

   public void TestCall()
   {
   }
}

Similarly, a static method cannot call an instance method unless you explicitly give it an instance of the class, as follows:

// CS0120_3.cs
using System;

public class MyClass
{
   public static void Main()
   {
      do_it("Hello There");   // CS0120
   }

   private void do_it(string sText)
   // You could also add the keyword static to the method definition:
   // private static void do_it(string sText)
   {
      Console.WriteLine(sText);
   }
}

Community Additions

ADD
Show:
© 2015 Microsoft