Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: "an object reference is required for the non-static field, method or property..." [duplicate]

Tags:

c#

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;         }     } } 
like image 308
user300484 Avatar asked Mar 24 '10 03:03

user300484


2 Answers

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) 
like image 196
Igby Largeman Avatar answered Sep 21 '22 11:09

Igby Largeman


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  } 
like image 22
Sugar Bowl Avatar answered Sep 21 '22 11:09

Sugar Bowl