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

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

Linda Hamilton
Release: 2025-01-22 17:46:11
Original
540 people have browsed it

Why Does

Error: "An Object Reference is Required for the Non-Static Field, Method, or Property..."

In C#, the error "an object reference is required for the non-static field, method, or property..." arises when attempting to access a non-static member from a static method. This error occurs due to the inability of static methods to access instance-specific data.

In the provided code snippet, the issue arises within the "Main" method, which is declared static, while the "volteado" and "siprimo" methods are non-static. To resolve this error, the "siprimo" and "volteado" methods must be declared static. By adding the "static" keyword, these methods can be accessed directly within the static "Main" method. Here's the corrected code:

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Write a number: ");
            long a = Convert.ToInt64(Console.ReadLine()); // a is the number given by the user

            long av = volteado(a); // av is "a" but swapped

            if (siprimo(a) == false && siprimo(av) == false)
                Console.WriteLine("Both original and swapped numbers are prime.");
            else
                Console.WriteLine("One of the numbers isn't prime.");
            Console.ReadLine();
        }

        private static bool siprimo(long a) // Declare siprimo as static
        {
            // Evaluate if the received number is prime
            bool sp = true;
            for (long k = 2; k <= a / 2; k++)
                if (a % k == 0) sp = false;
            return sp;
        }

        private static long volteado(long a) // Declare volteado as static
        {
            // Swap the received number
            long v = 0;
            while (a > 0)
            {
                v = 10 * v + a % 10;
                a /= 10;
            }
            return v;
        }
    }
}
Copy after login

The above is the detailed content of Why Does 'An Object Reference is Required...' Occur When Calling Non-Static Methods 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template