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

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 by following 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:\Users\Senthil\source\repos\ConsoleApp1\ConsoleApp1\Program.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.

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...