Tom Tom - 19 days ago 6
C# Question

How can I update the variable behind the referenced?

I might ask for the impossible here, but I wonder if I can update the variable behind the reference in any way.

Code example (C#) says more than a weird explanation:

var actual = "world";
var reference = actual;

reference = "you";

Console.WriteLine("Hello {0}", actual);


Outputs
"Hello world"
and not
"Hello you"
.

https://dotnetfiddle.net/3yERkY

Answer

You can if you use reference type but not with string
string is reference type but exceptionally it is immutable -> every time you "updating" it, new instance of string will be created.

    var actual = "world";
    var reference = actual;

    var isSame = ReferenceEquals(actual, reference);
    Console.WriteLine(isSame); // True

    reference = "you";
    Console.WriteLine("updated...");

    isSame = ReferenceEquals(actual, reference);
    Console.WriteLine(isSame); // False

You can create and use own type

public class MyValue
{
    public string Value { get; set; }
}

var actual = new MyValue { Value = "world" };
var reference = actual;

reference.Value = "you";

Console.WriteLine($"Hello {actual.Value}"); // Hello you