.NET Fiddle

CSharp · Console

/Program.cs

using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;


GCHandle weakHandle;
CreateCustomerAndPrintIt();
GC.Collect();
GC.WaitForPendingFinalizers();

if (weakHandle.Target is null)
{
    Console.WriteLine("Customer has been garbage collected (expected behavior).");
}
else
{
    Console.WriteLine("Customer is still alive (unexpected in this example).");
}


[MethodImpl(MethodImplOptions.NoInlining)]
void CreateCustomerAndPrintIt()
{
    Customer? customer = new()
    {
        Email = "[email protected]",
        Id = 1,
        UId = Guid.NewGuid().ToString()
    };
    Console.WriteLine($"Before creating weak handle: {customer}");
    weakHandle = GCHandle.Alloc(customer, GCHandleType.Weak);
    Console.WriteLine($"WeakHandle.IsAllocated: {weakHandle.IsAllocated}");
}
public sealed record class Customer
{
    public int Id { get; set; }
    public required string UId { get; set; }
    public required string Email { get; set; }
}
;