Tell if an instance is pointed to by other variables?

Viewed 59

This is a longshot but...

I understand there is a way to tell if variable A (var1, var2...., varX) points to instance of class by using Equals:

        List<string> _mainInstance = new();
        var var1 = _mainInstance;
        var var2 = _mainInstance;
        var var3 = _mainInstance;

        //I understand how to tell if variable points to _mainInstance
        if (var1.Equals(_mainInstance))
        {
            //It does because it points by reference
        }

        //I want to check if any variable still point to _mainInstance
        if (!_mainInstance.HasOthersPointingToIt())
        {
            //Safe to delete _mainInstance
        }

I don't know at design time how many pointers to _myInstance there will be. I want to check if my _mainInstance has any variables still pointing to it every so often. I thought maybe reflection or garbage collection but all my research there is coming up with nothing.

Is there a way to examine a variable (in this case an instance of a class) and tell if anything else (variables, properties of a class instance) still point to it?

Edit: @GuruStron asks what is the underlying problem I am trying to solve?

Answer: I have a parent/child "tree" that I need to keep track of. That in itself is pretty easy. My difficulty is that the tree has blocks that have a single definition and that definition gets reused.

In the graph below it shows the top tree with stars. The stars represents pointers to block definitions. Below that on the left are the actual block definitions.

enter image description here

The the block definition gets substituted and the final tree looks like this:

enter image description here

When a block pointer is deleted I need to make sure that nothing else is pointing to that block definition and delete the block definition when it is no longer needed.

0 Answers
Related