Tom Tom - 1 year ago 82
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);

"Hello world"
and not
"Hello you"

Answer Source

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";

    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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download