Reputation: 4303
From MSDN document i understand ( I am not sure,i understand perfectly ) :
Static members can operate only on static data and call static methods of the
defining class.
class Test
{
static int i;
public static void StaticDemo()
{
int v;
i=10;
v=10*i;
Console.WriteLine("The value of i={0}",v);
}
}
In the above example the declaration int v inside the method StaticDemo( ) is not static field. Then how did the operation v = 10 * i work ?
Upvotes: 1
Views: 401
Reputation: 13527
Because it doesn't have any scope beyond the static method. In other words, there is no state being kept on the method
Upvotes: -1
Reputation: 146557
Because variables defined inside a method are not either static or instance... They are locally scoped to the method itself.
They are stored in the method's stack frame, and have nothing to do either with the instance, or with the class.
Upvotes: 1
Reputation: 2725
Functions can always operate on local variables irrespective of whether they are static. Since v is declared within your StaticDemo function it is a local variable (i.e. only accessible within the function).
What the documentation is referring to is that you cannot access instance variables within a static method. So if instead of declaring i as 'static int i;' you had declared it as 'int i;' the StaticDemo method would not have been able to access it, since it would be an instance variable (i.e. not static).
Upvotes: 3
Reputation: 106916
Because v
does not belong to the defining class but to the method and thus can be operated on by the method.
Upvotes: 2
Reputation: 97801
It works because v is local to the static function itself. If v was defined in the body of the Test class, it would not.
Upvotes: 1
Reputation: 217371
The MSDN documentation refers to the fact that you cannot access instance members within a static method if you don't pass in an instance. Of course, every method can declare local variables and use them.
Upvotes: 10
Reputation: 38129
The int v
is local to the function, and therefore not a class member as such. (I.e. it doesn't need an instance of the class)
Upvotes: 5