"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why Does My C# Code Throw "An Object Reference Is Required for the Non-static Field, Method, or Property" Error?

Why Does My C# Code Throw "An Object Reference Is Required for the Non-static Field, Method, or Property" Error?

Posted on 2025-02-06
Browse:186

Why Does My C# Code Throw

C# Error: "Object reference is required to access non-static fields, methods, or properties"

]

In this C# code, an error occurred in the Population[i].bits = GetRandomBits(); line in the Main() method, and the error message is "Object reference is required to be used Accessing non-static fields, methods, or attribute 'VM_Placement.Program.GetRandomBits()'". This error indicates that a non-static method GetRandomBits() is being called from the static Main() method.

In C#, static methods are associated with classes, not with specific instances of classes, and not with static methods are associated with instances of classes. This means that non-static methods require instances of the class to be called.

For this specific case, there are two solutions to resolve this error:

  • Create an instance of the Program class:
Program p = new Program();
p.GetRandomBits();

By creating an instance of the Program class, you can call GetRandomBits() on that instance because it is now an instance method.

  • Set the GetRandomBits() method to static:
public static string GetRandomBits()
{
    // ...
}

Set GetRandomBits() to static, allowing it to be called directly in the static Main() method without the need for instance of the class.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3