tags:

views:

191

answers:

2

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?

+20  A: 

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
Jon Skeet
this answer has already been accepted. You just haven't clicked it yet :-D
David Archer
+7  A: 

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.

Eric Lippert
@Eric: As mentioned by Jon, this is a local variable and it will have scope only in the C method. So I still believe that 'static method can work only on static members'. What do you say.
vaibhav
@vaibhav: I give a legal example of a static method doing work on non-static members. Therefore it cannot be true that a static method can work only on static members.
Eric Lippert
@vaibhav: Perhaps it would be helpful to make Eric's point totally explicit: `x` is an instance member of type `C`, and yet this instance member is legally used within static method `Factory`. The fact that `c` is a local is irrelevant to this point (it could just as easily have been passed in to the method as an argument, for example); what is important is that it is perfectly valid to use the member `x` even though it is not a static member. You can not use an instance member without providing an instance, of course, if that is what you really mean by your objection.
kvb