Home > Backend Development > C++ > Why Does 'An Object Reference is Required' Appear When Calling a Non-Static Method from a Static Method in C#?

Why Does 'An Object Reference is Required' Appear When Calling a Non-Static Method from a Static Method in C#?

DDD
Release: 2025-01-22 05:24:16
Original
193 people have browsed it

Why Does

C# code error: "An object reference is required to access a non-static field, method, or property"

The provided code snippet throws an error in Class 2 (Implementing Algorithm) due to an attempt to access a non-static method Main() from a static method GetRandomBits().

In the Main() method, the line Population[i].bits = GetRandomBits(); caused the error. The problem is that GetRandomBits() is a non-static method in the Program class, while Main() is a static method.

Solution: static vs. non-static

  • Non-static methods: Must be called from an instance (object) of a class.
  • Static methods: can be called directly from the class name without creating an instance.

Solution:

  1. Create instance: Create an instance of the Program class and call GetRandomBits() from that instance.
<code class="language-csharp">// 创建 Program 实例
Program p = new Program();

// 从实例访问非静态方法
Population[i].bits = p.GetRandomBits();</code>
Copy after login
  1. Make GetRandomBits() static: Modify the static method to a static method by adding the GetRandomBits() keyword before the method declaration.
<code class="language-csharp">public static string GetRandomBits()
{
    // 在此处实现方法逻辑...
}</code>
Copy after login

Which method you choose depends on your program design and the purpose of the GetRandomBits() method. If GetRandomBits() needs to access other non-static members of the class, it must use the first method (create instance). If GetRandomBits() doesn't need to access non-static members of the class, the second approach (making it static) is cleaner. Remember, overuse of static methods may make your code less testable and maintainable.

The above is the detailed content of Why Does 'An Object Reference is Required' Appear When Calling a Non-Static Method from a Static Method in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template