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
Solution
To fix the CS0120 Error in C#, avoid accessing the non-static member directly from the static method.