Question

my question is probably very basic but I did not find an answer...

I wrote a function (public checkSomething that gets 2 strings) in program.cs when I tried to call this function from static main I got this error:

"An object reference is required for a non-static field, method or property 'checkSomething(string,string)' ".

However,when I changed my main to Public (and not static)- there is no error. Why this happen? What is better - to have a Static main or not? Why would it even matter?

thanks!

Was it helpful?

Solution

The question here is not about static functions, but specifically why is main static in a C# application.

It has to do with having only one thread for the main application. This is defined when using the [STAThread] attribute on the main function. The executing thread enters the main function only once, and no instance of the Program class is required.

The static main function can then instantiate any classes it requires for normal operation. These are often things like forms, or worker classes.

The program either enter a message loop in the main thread to process a visible form, or the program terminates.

When you remove the static reference for main the build options for the project switch from a startup function to a startup object, and an instance of the class is created before main is called.

It's a matter of personal preference, but keep in mind that only 1 main is ever executed during start up.

OTHER TIPS

Main method should be static so you can't call non static methods from static method.

change checkSomething to static.

if main method is not static then we need to create instance to call the main method. To create instant again we need to excute some code! Thats why I think this starting point Main make Static.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top