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

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...