0

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

Ryan Bemrose
  • 9,018
  • 1
  • 41
  • 54
Tom
  • 869
  • 6
  • 25
  • Strings behave like value type in C#. Although C# 7, has improved reference support, I don't think it is possible to have a reference to a local variable. – Phil1970 Nov 19 '16 at 20:45
  • @Phil1970 No they don't strings act like refrences. If you do `var actual = new Foo(1);`, `var reference = actual;`, `reference = new Foo(2);` you would not expect `actual` to be updated to `Foo(2)` either. You just need to remember that doing `"you"` is behind the scenes is the same as a `new String(` call. – Scott Chamberlain Nov 19 '16 at 21:54
  • @ScottChamberlain The behavior of some operations is the one of value type (for example == operator). See also [In C#, why is String a reference type that behaves like a value type?](http://stackoverflow.com/questions/636932/in-c-why-is-string-a-reference-type-that-behaves-like-a-value-type). So they have value semantic. If you compare with a language like C++, the behavior would be more similar to `std::string` than to `std::string &`... – Phil1970 Nov 20 '16 at 02:49

1 Answers1

1

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
Fabio
  • 31,528
  • 4
  • 33
  • 72