nilllzz
nilllzz

Reputation: 205

Assign object to reference inside variable, instead the variable

Basically, I get a reference to a field of an object that is stored inside an array and put that into a variable.

Then, I want to assign a different object reference to the field by assigning it to the variable I stored the field in earlier.

To illustrate my point, here's a simple example:

    class myClass
    {
        public object obj = null;
    }

    class someOtherClass
    {  }

...

    static void Main(string[] args)
    {
        myClass[] arr = new myClass[] { new myClass() };
        var objVar = arr[0].obj;
        objVar = new someOtherClass();
    }

I get the field from the object from the array and store it in a variable.

Now, I want to store a new value in the field by assigning the variable.

What actually happens though is that the variable does not keep the reference to the field, but rather just assigns the object of someOtherClass to the variable, removing the field from the varible.

So after this code executed, field obj of the myClass instance is still null, while the variable objVar contains a reference to my someOtherClass instance.

Is there an easy way to assign a reference to a reference inside a variable like this?

Upvotes: 0

Views: 97

Answers (3)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112324

I see these possibilities:

  1. Store the index:

    int i = 0;
    arr[i].obj new someOtherClass();
    
  2. Store the object whose property you want to change

    var objVar = arr[0]; // NOT arr[0].obj !
    objVar.obj = new someOtherClass();
    
  3. If you want to choose the property dynamically, i.e. the property is not always the same, then use @Blorgbeard's answer.

Upvotes: 2

Blorgbeard
Blorgbeard

Reputation: 103447

You could use a trick with a lambda expression:

var setter = x => arr[0].obj = x;
setter(new someOtherClass());

You could even use a generic wrapper class, something like this:

class Reference<T> {

    private Action<T> setter;
    private Func<T> getter;

    public Reference(Action<T> setter, Func<T> getter) {
        this.setter = setter;
        this.getter = getter;
    }

    public T Value {
        get {
            return getter();
        }
        set {
            setter(value);
        }
    }
}

And then:

var objVar = new Reference<object>(t => arr[0].obj = t, () => arr[0].obj);
objVar.Value = new someOtherClass();

See fiddle here: https://dotnetfiddle.net/HXJJQf

Upvotes: 3

Rolando Retana
Rolando Retana

Reputation: 492

I think you need to copy the value, implementing something like this: Deep cloning objects

Upvotes: 0

Related Questions