C#C
C#3mo ago
hugeman

ValueType disposable scope

Is there a safe way to use a value type to manage a disposable "scope"? For example in this code, it should write "1" to the console, but it actually writes "2" because it creates a copy of scope1 and disposes it:
private static int disposeCount = 0;

public ref struct Scope(object myObject) {
    private object? myObject = myObject;

    public void Dispose() {
        object? obj = myObject;
        if (obj != null) {
            myObject = null;
            disposeCount++;
        }
    }
}

public static void Main() {
    using (Scope scope1 = new Scope("some object")) {
        Scope scope2 = scope1;
        scope2.Dispose();
    }

    Console.WriteLine(disposeCount);
}
Was this page helpful?