Compiler Error CS0120

An object reference is required for the non-static 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 about static methods, see Static Classes and Static Class Members. For more information about creating instances of classes, see Instance Constructors.

Example 1

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
    }
}

To correct this error, first create an instance of the class:

// 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()
    {
        var mc = new MyClass();
        mc.i = 10;
        mc.f();
        int p = mc.Prop;
    }
}

Example 2

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
   }

   public void TestCall()
   {
   }
}

To correct this error, first create an instance of the class:

// CS0120_2.cs
using System;

public class MyClass
{
    public static void Main()
    {
        var anInstanceofMyClass = new MyClass();
        anInstanceofMyClass.TestCall();
    }

    public void TestCall()
    {
    }
}

Example 3

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()
   {
      DoIt("Hello There");   // CS0120
   }
  
   private void DoIt(string sText)
   {
      Console.WriteLine(sText);
   }
}

To correct this error, you could also add the keyword static to the method definition:

// CS0120_3.cs
using System;

public class MyClass
{
   public static void Main()
   {
      DoIt("Hello There");   // CS0120
   }
  
   private static void DoIt(string sText)
   {
      Console.WriteLine(sText);
   }
}

See also