Nik Dell
Nik Dell

Reputation: 53

C# Destroy object and all references to it

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; }
}

Upvotes: 4

Views: 2165

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500675

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.

Upvotes: 6

Related Questions