Tom
Tom

Reputation: 950

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

Upvotes: 0

Views: 77

Answers (1)

Fabio
Fabio

Reputation: 32445

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

Upvotes: 1

Related Questions