c# Is it possible get a reference of an object, get the object itself and change it, instead of assinging to a new object?

I'm just curious if something like that is possible in c#. I don't know why would anybody want to do it, but it's still interesting if that can be done.:

public class Test
{
    public string TestString { private set; get; }
    public Test(string val) { TestString = val; }
}

    public class IsItPossible
    {
        public void IsItPossible()
        {
            Test a = new Test("original");
            var b = a;
            //instead of assigning be to new object, I want to get where b is pointing and change the original object
            b = new Test("Changed"); // this will assign "b" to a new object", "a" will stay the same. We want to change "a" through "b"
            //now they will point to different things
            b.Equals(a); // will be false
            //what I'm curious about is getting where b is pointing and changing the object itself, not making just b to point to a new object
            //obviously, don't touch a, that's the whole point of this challenge

            b = a;
            //some magic function
            ReplaceOriginalObject(b, new Test("Changed"));
            if (a.TestString == "Changed" && a.Equals(b)) Console.WriteLine("Success");
        }
    }
Jon Skeet
people
quotationmark

If you mean "can I change the value of a to refer to a different object, simply by changing the value of b?" then the answer is no.

It's important to understand that the value of a variable is never an object - always either a value type value or a reference. I like to think of variables like pieces of paper, and objects like houses.

A piece of paper can have a value type value written on it (e.g. a number) or the address of a house. When you write:

var b = a;

that's creating a new sheet of paper (b) and copying what's written on sheet a onto sheet b. There are two things you can do at that point:

  • Change what's written on b. This doesn't affect what's written on a even tangentially
  • Go to the address written on b, and modify the house (e.g. painting the front door). This doesn't change what's written on a either, but it does mean that when you visit the address written on a you'll see the changes (because you're going to the same house).

This is assuming "regular" variables, mind you - if you use ref parameters you're effectively making one variable an alias for another. So for example:

Test a = new Test("Original");
ChangeMe(ref a);
Conosole.WriteLine(a.TestString); // Changed

...

static void ChangeMe(ref Test b)
{
    b = new Test("Changed"); // This will change the value of a!
}

Here we effectively have one sheet of paper, with names a (in the calling code) and b (in the method).

people

See more on this question at Stackoverflow