Nidere
Nidere

Reputation: 129

Is there a way to change referenced value so that all references would be updated?

I want to declare local variables, add them to a List and then pass to a method that changes objects that are referenced by that list's elements.

However I need the original variables to reflect those changes, and they do not.

Is that even possible? Thanks a lot

class TestObject
{
    public int test;

    static TestObject test3 = new TestObject { test = 3 };
    static TestObject test4 = new TestObject { test = 4 };

    public static void Test()
    {
        TestObject test1 = new TestObject { test = 1 };
        TestObject test2 = new TestObject { test = 2 };

        List<TestObject> list = new List<TestObject>() { test1, test2 };

        Test2(list); // list[0] = 3 and list[1] = 4, but test1 still = 1 and test2 = 2
    }

    public static void Test2(List<TestObject> list)
    {
        list[0] = test3;
        list[1] = test4;
    }
}

Upvotes: 0

Views: 161

Answers (1)

Tolik Pylypchuk
Tolik Pylypchuk

Reputation: 680

As people pointed out in the comments to the question, you probably don't need to reassign references if they are changed in the list - there may be a better solution for your problem. But if you do know that this is the way to go - that you need to fully replace the objects in the list and have those changes reflected elsewhere, then you can use a simple proxy and pass a list of proxies instead of a list of your objects.

public class Proxy<T>
{
    public Proxy(T obj)
    {
        this.Reference = obj;
    }

    public T Reference { get; set; }
}

This way you can create a list of proxies:

var test1 = new Proxy<TestObject>(new TestObject { test = 1 });
var test2 = new Proxy<TestObject>(new TestObject { test = 2 });

var list = new List<Proxy<TestObject>>() { test1, test2 };

And later you can reassign the values as you wish:

public static void Test2(List<Proxy<TestObject>> list)
{
    list[0].Reference = test3;
    list[1].Reference = test4;
}

Now after the method has returned, test1 and test2 will (indirectly) reference the new objects.

Having said that, I'd say that I think it's cumbersome and hacky - I'd rather change the actual objects than references to them (the proxies do just that).

Upvotes: 1

Related Questions