Storing a reference in c#

Adam Naylor picture Adam Naylor · Dec 8, 2009 · Viewed 7.4k times · Source

I'm trying to design a class which can update a reference to an object (outside the class) on destruction.

So essentially you create an instance of this object and pass it a reference type (in whichever manner, constructor etc.) and then on destruction of the object the original reference has changed to a reference created by the object.

If I pass a reference by reference (say in construction) I can't figure a way to store this reference (as a reference) for the destructor to update it? For example (pseudo):

class Updater
{
    object privateReference;
    public Updater(ref object externalReference)
    {
        privateReference = externalReference; //is privateReference now a new reference to the original object?
    }

    ~Updater()
    {
        privateReference = new object(); //therefore this isn't 'repointing' the externalReference
    }
}

The key here is I'm not trying to mutate the original 'external' object from this class I'm trying to 'repoint' it, or initialise it if you will.

Answer

Jon Skeet picture Jon Skeet · Dec 8, 2009

You can't do this, basically. ref is only applicable within the method itself, effectively.

It's not at all clear what you want to use this for - could you give us more information so we can suggest alternative designs? Anything which relies on a finalizer is troubling to start with, to be honest...