MaT
MaT

Reputation: 1606

Store object string reference

I think this question was asked many times in C# but my problem is maybe more solvable.
I have an object value as a string : myobject.value and I want to store this value in a queue (or anything else) to access it later. Is it possible?

I read a lot of posts saying that it is not possible to store a ref to a string. I don't see any solution to store a ref to my string value myobject.value and change it later.

Any Ideas ?

Upvotes: 1

Views: 603

Answers (2)

Adam Houldsworth
Adam Houldsworth

Reputation: 64557

If you want to store a reference to a string that people can see and share the changes of you will need to wrap it in a class:

public class Wrapper<T>
{
    public T Item { get; set; }
}

Then people use this instead of a string:

class MyClass
{
    public Wrapped<string> SharedString { get; set; } 
}

var c1 = new MyClass();
var c2 = new MyClass();

var s = new Wrapped<string> { Item = "Hello" };

c1.SharedString = s;
c2.SharedString = s;

c1.SharedString.Item = "World";
Console.Writeline(c2.SharedString.Item);

Even though strings are reference types, they are immutable so changes need to the "copied" around. Sharing is this way doesn't change the immutability, it just centrally holds one copy of a string that everyone is looking at via their reference to Wrapped<string>.

You can take the Wrapped<T> class further and give it implicit cast support to and from T, for a little syntactic sugar:

public static implicit operator T(Wrapped<T> wrapper)
{
    return wrapper.Item;
}

public static implicit operator Wrapped<T>(T item)
{
    return new Wrapped<T> { Item = item };
}

Wrapped<int> i = 2;
int j = i;

// Careful, this is a re-assignment of s, not a change of s.Item.
Wrapped<string> s = "Hello"; 

Upvotes: 3

If I understand you right, and myobject.value is a string, than you can certainly store a collection representing those values

List<string> strLst = new List<string>();
strLst.Add(`myobject.value`);

No, you can't store a reference as a string, nor should you have to, but you can make a string(or xml) that represents all the information about your object, if you really need to.

Upvotes: 0

Related Questions