0

I'm keeping track of a node object that I would like to change later (to a different type and hence re-assign it). It's from an element of an array that I later won't have access to.

I can't just keep track of the object and re-assign it because that will just re-assign the variable and not the actual object that's part of the array. I'm basically looking for ref-like semantics but without using methods.

My current workaround is just keeping track of the array the element is a part of and the index the object is at but having two variables just to do this seems kind of messy. Surely there is a better way?

John Smith
  • 8,567
  • 13
  • 51
  • 74

1 Answers1

2

You can use delegate to store destination (this work with any other types/scenarios too, including "can't pass property by reference" case):

var captureIndex = index; 
var captureArray = array;
Action<string> updateItLaterWith = v => captureArray[captureIndex] = v;

// ....And when finally decided to update 
updateItLaterWith("Done!!!");

Sample shows protection against capturing wrong values (i.e. if index changes later, but before call to the delegate), you may not need such complexity and v => array[index]; could be enough.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179