Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are variables in the main methods static

Tags:

c#

.net

static

Its a well known fact that a static method can work only on static members.

public static void Main()
{
    Test t1 = new Test();
}

Here the Main method is static, but I haven't declared t1 as static. Is it implicitly static?

like image 898
Vaibhav Jain Avatar asked Apr 16 '10 09:04

Vaibhav Jain


2 Answers

No, it's a local variable. Local variables behave the same way whether they're declared in static methods or instance methods.

As a very rough guide (captured variables etc introduce complications):

  • Instance variables: one variable per instance
  • Static variables: one variable for the type itself
  • Local variables (including parameters): one separate variable for each method call
like image 187
Jon Skeet Avatar answered Oct 05 '22 21:10

Jon Skeet


Its a well known fact that a static method can work only on static members

This is not a fact; this is a falsehood. There is no restriction whatsoever; static methods have full access to all members of their type:

class C 
{
    private int x;
    static C Factory()
    {
        C c = new C();
        c.x = 123;
    }
}

Factory is a static method; it has access to the private instance members of any instance of C.

like image 29
Eric Lippert Avatar answered Oct 05 '22 22:10

Eric Lippert