C# Error: "An object reference is required to access a non-static field, method, or property"
In this C# code, an error occurs at the Main()
line within the Population[i].bits = GetRandomBits();
method. The error message is "An object reference is required to access non-static fields, methods or properties 'VM_Placement.Program.GetRandomBits()'". This error indicates that a non-static method Main()
is being called from a static GetRandomBits()
method.
In C#, static methods are associated with a class rather than with a specific instance of the class, while non-static methods are associated with instances of the class. This means that non-static methods require an instance of the class in order to be called.
For this specific case, there are two solutions to resolve this error:
<code class="language-csharp">Program p = new Program(); p.GetRandomBits();</code>
By creating an instance of the Program class, GetRandomBits()
can be called on that instance since it is now an instance method.
<code class="language-csharp">public static string GetRandomBits() { // ... }</code>
Make GetRandomBits()
static, allowing it to be called directly from a static Main()
method without requiring an instance of the class.
The above is the detailed content of Why Does My C# Code Throw 'An Object Reference Is Required for the Non-static Field, Method, or Property' Error?. For more information, please follow other related articles on the PHP Chinese website!