1

Why does b.b would not change to "a2" as with f.f?

Thanks.

public class Test
{
    public static void Main()
    {
        Foo f = new Foo
        {
            f = getStr()
        };

        Boo b = new Boo
        {
            b = f.f
        };


        f.f = "a2";

        Console.WriteLine(f.f);
        Console.WriteLine(b.b);
    }

    public static string getStr()
    {
        string a = "a1";
        return a;
    }
}

public class Foo
{
    public string f { get; set; }
}

public class Boo
{
    public string b { get; set; }
}
Ricky
  • 34,377
  • 39
  • 91
  • 131

4 Answers4

3

Here's a simpler piece of code demonstrating what I think you're expecting to see:

string x = "hello";
string y = x;
x = "there";

You appear to expect y to be "there" at this point. But x and y are entirely independent variables - the assignment in the second merely copies the value of x (a reference to a string "hello") to y. The third line assigns a different value to x (a reference to a string "there") - it doesn't change the value of y, which is still a referent to a string "hello".

Your example is more complicated as it's using separate types with automatically implemented properties - but the fundamental concepts are the same.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

Boo.b and Foo.f are strings, not pointers to strings.
Assigning Foo.f to Boo.b assigns the value of Foo.f to Boo.b. After that assignment, they are independent. Changing Foo.f will not change Boo.b.

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
1

Strings in .NET is immutable, that means, you are not sending the reference, but the value.

In other classes in .NET, you are passing references. Like this:

Car c = new Car();
c.Name = "Ford";
var d = c;
d.Name = "Volvo";
c.Name; //Volvo

but in string, it is working like this:

string s = "Hey";
string c = s;
c = "World!";
//s is still "Hey"

Look at this question for more information: Why .NET String is immutable?

It is, of course, the same with other classes.

Car c = new Car();
c.Name = "Ford";
Car d = c;
//d.Name == "Ford";
d = new Car();
d.Name = "Volvo";
//c.Name is still "Ford"
Community
  • 1
  • 1
Jan Sverre
  • 4,617
  • 1
  • 22
  • 28
0

Why would it? You're not changing it. Just because you set b.b to f.f in the past, doesn't mean it'll keep udpating it with any changes.

You set a value, not a reference.

Flynn1179
  • 11,925
  • 6
  • 38
  • 74