public class Class1
{
public static string Name="foo";
public void ChangeName(string _name)
{
Name=_name;
}
}
in some other class..
Class1 _c=new Class1();
_c.ChangeName("bar");
and the Name gets changed.. an instance changing a static member!
I thought a static member is available only for a Class. If a Class wants it can change its static members.
But here an instance is able to change it indirectly.Shouldn’t an instance not be able to change it? When we create an instance it occupies its own space in the heap without having access to the static members of the Class. So what is really happening here?
No, an instance is not kept from accessing static members. Instances are separate from each other, but static members are available both to static methods and instance methods.
As you have made it public, it’s not even only methods in the class itself that can access it. You can change it from anywhere: