Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot call a function from a static method

Ok, this may sound like a very novice question.. i'm actually surprised i'm asking it. I can't seem to remember how to call a function from inside static void Main()

namespace myNameSpace
{
    class Program
    {
         static void Main()
         {
              Run(); // I receive an error here.
              Console.ReadLine();
         }
         void Run()
         {
              Console.WriteLine("Hello World!");
         }
    }
}

error:

An object reference is required for the non-static field, method, or property 'myNameSpace.Program.Run()'

like image 735
rlemon Avatar asked Dec 05 '22 20:12

rlemon


2 Answers

You need to either make Run a static method or you need an object instance to call Run() of. So your alternatives are:

1.) Use an instance:

new Program().Run();

2.) Make Run() static:

static void Run()
{
   /..
}
like image 160
BrokenGlass Avatar answered Dec 26 '22 21:12

BrokenGlass


Declare your Run() method as static too:

static void Run()
{
   Console.WriteLine("Hello World!");
}
like image 43
evilone Avatar answered Dec 26 '22 22:12

evilone