35

I'm creating an application in C#. Its function is to evaluate if a given is prime and if the same swapped number is prime as well.

When I build my solution in Visual Studio, it says that "an object reference is required for the non-static field, method or property...". I'm having this problem with the "volteado" and "siprimo" methods.

Where is the problem and how can I fix it?

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 isnt prime.");
            Console.ReadLine();
        }

        private bool siprimo(long a)
        {
            // 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 long volteado(long a)
        {
            // Swap the received number
            long v = 0;
            while (a > 0)
            {
                v = 10 * v + a % 10;
                a /= 10;
            }
            return v;
        }
    }
}
3
  • 2
    Welcome to StackOverflow! Please use more descriptive question names in the future :)
    – Matchu
    Commented Mar 24, 2010 at 3:38
  • Please edit your question for formatting. The first few lines of your code is not covered by the code format.
    – Chry Cheng
    Commented Mar 24, 2010 at 3:38
  • 3
    Made relevant formatting, title edits :)
    – Matchu
    Commented Mar 24, 2010 at 3:39

6 Answers 6

81

You can't access non-static members from a static method. (Note that Main() is static, which is a requirement of .Net). Just make siprimo and volteado static, by placing the static keyword in front of them. e.g.:

 static private long volteado(long a)
4
  • @user300484 you should mark this answer as correct by clicking the check below the rating.
    – mxmissile
    Commented Mar 24, 2010 at 3:55
  • 5
    The real answer to this question is provided by shazia, this is a workaround with no programming sense Commented Aug 29, 2012 at 14:15
  • It make sense when you're writing a quick throw-away console program. Commented Jan 31, 2021 at 20:33
  • Answer is to the point and correct, detailed answer can be found here link
    – Ali
    Commented Apr 20, 2023 at 17:17
39

Create a class and put all your code in there and call an instance of this class from the Main :

static void Main(string[] args)
{

    MyClass cls  = new MyClass();
    Console.Write("Write a number: ");
    long a= Convert.ToInt64(Console.ReadLine()); // a is the number given by the user
    long av = cls.volteado(a);
    bool isTrue = cls.siprimo(a);
    ......etc

}
3
  • 7
    This is the real solution to this problem Commented Aug 29, 2012 at 14:15
  • Yes, in the long term and as good practice you should encapsulate it on a class.
    – Patricio
    Commented Jul 16, 2017 at 10:36
  • this one fixed my issue.
    – chesco
    Commented May 26, 2020 at 2:08
21

Simply add static in the declaration of these two methods and the compile time error will disappear!

By default in C# methods are instance methods, and they receive the implicit "self" argument. By making them static, no such argument is needed (nor available), and the method must then of course refrain from accessing any instance (non-static) objects or methods of the class.

More info on static methods
Provided the class and the method's access modifiers (public vs. private) are ok, a static method can then be called from anywhere without having to previously instantiate a instance of the class. In other words static methods are used with the following syntax:

    className.classMethod(arguments)
rather than
    someInstanceVariable.classMethod(arguments)

A classical example of static methods are found in the System.Math class, whereby we can call a bunch of these methods like

   Math.Sqrt(2)
   Math.Cos(Math.PI)

without ever instantiating a "Math" class (in fact I don't even know if such an instance is possible)

1
  • 4
    +1 for giving insight to the issue rather than just a quick-fix: this is much more useful for a newcomer to C# that is still learning the basics. I have two side comments, however: 1) Math is a static class (msdn.microsoft.com/en-us/library/system.math.aspx) so your suspicion is right: it can't be instantiated; and 2) maybe you should provide some example of instance methods... the ubiquitous ToString() comes to mind. Commented Mar 24, 2010 at 4:51
3

Change your signatures to private static bool siprimo(long a) and private static long volteado(long a) and see where that gets you.

0

You just need to make the siprimo and volteado methods static.

private static bool siprimo(long a)

and

private static long volteado(long a)
0

The error message means that you need to invoke volteado and siprimo on an instance of the Program class. E.g.:

...
Program p = new Program();
long av = p.volteado(a); // av is "a" but swapped

if (p.siprimo(a) == false && p.siprimo(av) == false)
...

They cannot be invoked directly from the Main method because Main is static while volteado and siprimo are not.

The easiest way to fix this is to make the volteado and siprimo methods static:

private static bool siprimo(long a)
{
    ...
}

private static bool volteado(long a)
{
   ...
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.