Link storage in C #

I am trying to create a class that can update the reference to an object (outside the class) upon destruction.

So, you create an instance of this object and pass it the reference type (in any way, constructor, etc.), and then when you destroy the object, the original link was changed to the link created by the object.

If I pass the link by reference (say, in the build), I can’t figure out how to save this link (as a link) 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 point here is that I am not trying to mutate the original “external” object from this class. I am trying to “reassign” it or initialize it if you do.

+6
c # reference-type
source share
3 answers

You cannot do this, basically. ref applicable only in the method itself.

It is not clear why you want to use this - could you give us more information so that we can offer alternative projects? Honestly, something that relies on a finalizer bothers you from the start ...

+7
source share

This will not work because the ref attribute of the constructor parameter is applied only within the constructor.

I would do to give the constructor a delegate that can be used to update the thing in question. In addition, you should use IDisposable for this (in combination with the using block), and not a finalizer; finalizers should not touch managed objects (they are designed to free unmanaged objects).

 class Updater : IDisposable { Action<object> setter; public Updater(Action<object> setter) { this.setter = setter; } public Dispose() { setter(new object()); } } 
+4
source share

Remember that using Finalizer like this does not match the destructor in C ++.

When the last link dies (maybe it goes beyond), the object goes into the Finalizer queue. GC determines when to call Finalizer, and it can be a long time after the last link ends.

+1
source share

All Articles