Reputation: 87
From my understanding passing a variable by reference means that the original variable that was passed into a function's parameters is changed. But also from my understanding a static variable means that the variable is changed when used as a parameter of a function. So don't both of these do the same thing?
Upvotes: 1
Views: 2133
Reputation: 1062865
From my understanding passing a variable by reference means that the original variable that was passed into a function's parameters is changed.
That location is passed, so yes; since the caller supplied the location, the caller can see the change.
But also from my understanding a static variable means that the variable is changed when used as a parameter of a function.
That's not what that means at all. A static field just exists as a field once per type (or per combination of generic type arguments). That's all it means. When you pass the value of a static field to a method, the value from the static field is read once and copied onto the stack, and that copy is passed to the method. The value of the static field will not be changed during the call.
Perhaps the confusion here is actually "reference types", not "pass by reference"; if a static field is actually a reference to an object, then changes to the object will be observed by all callers. But it isn't the field that changed: it is the object.
Upvotes: 4