rlemon
rlemon

Reputation: 17666

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()'

Upvotes: 4

Views: 5964

Answers (6)

Sandeep G B
Sandeep G B

Reputation: 4015

The other way is to encapsulate your Run() method inside a nested class and invoke it.

        static void Main(string[] args)
    {
        new NestedClass().Run();
    }

    class NestedClass
    {
        public void Run()
        { 
        }
    }

Upvotes: 0

Roee Gavirel
Roee Gavirel

Reputation: 19445

cause static function is not associate with an instance. while the none static function must have an instance.
So you have to create a new instance (each way you want) and then call the function.

Upvotes: 0

Scott Willeke
Scott Willeke

Reputation: 9335

Run() must also be static or you need to create a new instance of the object like new Program().Run();

Upvotes: 2

BrokenGlass
BrokenGlass

Reputation: 160852

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()
{
   /..
}

Upvotes: 7

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56162

Make method static: static void Run()

Upvotes: 2

evilone
evilone

Reputation: 22740

Declare your Run() method as static too:

static void Run()
{
   Console.WriteLine("Hello World!");
}

Upvotes: 5

Related Questions