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:
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.
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.
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