CRK CRK - 1 month ago 19
C# Question

Explanation Static Members

Why Class1.a is still null even if I referenced it and change its value? Strings are reference type so I think that changing is value will affect the reference but it's not true. Someone can explain me why? It's for the static declarator?

class Class1
{
public static string a;
}
void Main()
{
string a = Class1.a;
a = "hello";
MessageBox.Show(Class1.a);
}



Output: null

PMV PMV
Answer

You didn't change its value. You just made a copy of the null reference into a local variable, you set the local variable to refer to a new string, but in all of that you never changed the original reference to refer to anything other than null.

It's true that strings are a reference type, but even with reference types, changing the reference itself is different than changing a property on the object being referenced.

For example:

Foo a = new Foo ();
Foo b = a;
b.Bar = 7;
b = new Foo ();
b.Baz = 12;

In this example, a.Bar will be 7, since at the time a and b referenced the same object. However, a.Baz was not set to 12, because b was changed to refer to a different object. The variable a also still refers to the first object created, not the second.

String additionally doesn't let you modify the object (it is immutable), but that is an aside - the reason your code doesn't work is because you were modifying the reference, not modifying the object.