Reputation: 17666
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
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
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
Reputation: 9335
Run() must also be static or you need to create a new instance of the object like new Program().Run();
Upvotes: 2
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
Reputation: 22740
Declare your Run()
method as static too:
static void Run()
{
Console.WriteLine("Hello World!");
}
Upvotes: 5