© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•5mo ago•
38 replies
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
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);
}
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);
}
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,828Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

❔ Maybe Disposable Object
C#CC# / help
3y ago
✅ Disposable class level property
C#CC# / help
14mo ago
✅ is it a good disposable class?
C#CC# / help
3y ago
❔ IServiceProvider, scoped services, scopes
C#CC# / help
3y ago