Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi people. I have confusion understanding why when the Main method is static all the other methods must be static too ? Could someone explain that to me ?

What I have tried:

Asking a question here in CodeProject.com
Posted
Updated 28-May-17 8:47am

They aren't!

The main method must be static, because static methods do not need an instance of the class in order to be called - all non static methods require an instance of the class to be created before you can call them.
Since the main method is where your application starts, you can't create a class instance first (because the instance constructor would have to run before you could call the main method).

Once main has been called it can create instances, and call non-static methods on those instances:

static void main()
   {
   MyClass mc = new MyClass();
   ms.DoSomething();
   }
 
Share this answer
 
Comments
The_Unknown_Member 29-May-17 5:33am    
Thanks you man! Now I understood that there is no problem if i dont make my methods static in the class i will have to make instance of my class before use them. Like this for example:

using System;

class Program
{
static void Main(string[] args)
{
Program p = new Program();
p.divide(4, 2);
}

void divide(int a, int b)
{
Console.WriteLine(a / b);
}
}
OriginalGriff 29-May-17 5:43am    
You're welcome!
They don't need to be all static. Yet, the static method doesn't have an object (the this object) while the non-static methods have it.

You can very easily do:
C#
class Program
{
  static void Main()
  {
    var program = new Program();
    program.DoSomething();
  }

  void DoSomething()
  {
    // here this will be available, and will be the program
    // variable created in the Main call. Note that you could
    // create more than one instance of the Program class.
  }
}
 
Share this answer
 
Comments
The_Unknown_Member 29-May-17 5:33am    
Thank you also for the answer!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900