4

Below C# code

ResBlock resBlock1 = new ResBlock();                
resBlock1.CustomerID = "ABC";

Block block = new Block();
block.Tag = resBlock1;

resBlock1 = null;

Console.WriteLine(((ResBlock)block.Tag).CustomerID);

The output would be "ABC". Of course this is the example of what I am facing but my code is way more complicated.

What I would like to understand is if there is a way to get block.Tag = null when the referenced object (resBlock1) is set to null or destroyed in some other way (which one?).

Classes are very simple as this is just an example:

public class ResBlock: IDisposable
{
    public DateTime From { get; set; }
    public DateTime To { get; set; }
    public string CustomerID { get; set; }
    public string ItemID { get; set; }

    [...]

    public ResBlock() {
        DaysStatus = new List<ResBlockDayStatus>();
        Deleted = false;
    }

    public bool LogicallyDeleted { get; set; }

    public void Dispose() { }
}

public class Block
{        
    public bool Selected { get; set; }
    public object Tag { get; set; }
    public DateTime From { get; set; }
    public DateTime To { get; set; }
}
GSerg
  • 76,472
  • 17
  • 159
  • 346
Nik Dell
  • 53
  • 7
  • 1
    `when the referenced object (resBlock1) is set to null or destroyed in some other way` - you appear to think that setting the "original" reference to resBlock1 will destroy it. Not only would it not destroy it, there is also no difference between the "original" reference and any other reference that may appear during the lifetime of an object. Your `block.Tag` is just as worthy and original as the "original" `resBlock1`. – GSerg Apr 23 '20 at 10:19
  • 1
    You can't magically set all references to a specific object to null throughout a program, no. The correct way to do this is probably to keep a "disposed" boolean status inside the object, and, on disposing, enable that, and then cause that to make all functions of that object, getters and setters included, throw an `ObjectDisposedException` when called. Might want to create a public readonly "IsDisposed" property to query though; it's always nicer to be able to check than to have to handle exceptions. – Nyerguds Apr 23 '20 at 10:47
  • @Nyerguds: the property LogicallyDeleted would work kind of the way you suggest. Thx – Nik Dell Apr 23 '20 at 11:14
  • @NicolaDell'anna Except it should not be settable from the outside. But, yea, `IsDisposed` is the name used for this throughout the original .Net framework. – Nyerguds Apr 23 '20 at 12:16

1 Answers1

6

No. You can't "destroy" an object in that way. That's just not the way that object lifetimes work in .NET. You could potentially change the Tag property to a WeakReference. That would prevent the Tag property from keeping the object within the WeakReference alive... but you still wouldn't be able to actively request object destruction.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194