Skip to content

[API Proposal]: Solve the broken multi-interface Dispose lifetime problem with duck-typed dispose(...) keyword. #128182

Closed as not planned

Description

@AnorZaken

Background and motivation

It remains problematic that when a disposable class implements multiple interfaces, the lifetime of those interfaces could be subtly different, affected by dispose call order, but the current Dispose pattern is unable to handle that, because typically callers just cast to IDisposable and then call Dispose, meaning the context of what the caller thinks it is disposing is unknown to the implementation of the Dispose method.

The C# solution to a semi-similar problem, is when two interfaces have the same method signature, and then you solve it by explicit interface implementation --> this lets the implementation class differentiate what the caller thinks they are calling, and act accordingly. But since the pattern for IDisposable is to let the caller cast to the general IDisposable interface first, there is zero differentiation information available when the call reaches the implementing class.

In conclusion the dispose pattern is subtly broken under multi-interface inheritance in C#, and in hindsight the only way to correctly implement dispose semantics would have been to use Duck-Typing just as foreach does: Add a dispose(...) keyword similar to foreach(...) have it resolve Dispose via Duck-Typing just like foreach: If an interface has a Dispose method, it compiles. Now the implementing class can implement differentiated Dispose methods via explicit interface implementation, which solves the broken dispose pattern.

See this post for a simple code example of when the current Dispose pattern makes it impossible to handle lifetimes correctly:
#70004 (comment)

For backwards compatibility the new dispose keyword should check if casting to IDisposable is possible too, similar to using, but should prefer the duck-typed Dispose method on the compile-time type if it exists. Types where the compile-time type does not reveal a Dispose method should probably give compiler Warning or Information message, but not an error since it's probably best to have dispose work similar to using in that it silently does nothing at runtime if the runtime-type isn't disposable.

TL;DR: C# does not actually support a class to implement / inherit multiple disposable interfaces correctly.
At the very least we should have a code-analyzer warning for this.

API Proposal

// Since the "API" surface is compiler sugar, I'm not sure what exactly *that* code would look like,
// but here is the consumable surface example:
public record DisposeCallingConsumer(
        ISomeDisposableThing interface1,
        ISomeOtherDisposableThing interface2,
        SomeClassWithMultipleInterfaces theClass)
{
    void DisposeExample()
    {
        // (A record should not dispose like this, but just to keep the example code small and focused on the proposed syntax.)

        // Disposing via new proposed "dispose(...)" keyword that works with duck-typing similar to "foreach(...)":
        dispose(interface1); // <-- compiler looks for Dispose method on ISomeDisposableThing (duck-typing)
        dispose(interface2); // <-- compiler looks for Dispose method on ISomeOtherDisposableThing (duck-typing)
        dispose(theClass);// <-- compiler looks for Dispose method on SomeClassWithMultipleInterfaces (duck-typing)

        // In all calls above the implementing class knows what the caller (this) *thinks* it is disposing,
        // and can use explicit implementation to act accordingly.
    }
}

API Usage

public interface ISomeDisposableThing
{
    void DoSomethingElse();
    void Dispose();
}

public interface ISomeOtherDisposableThing
{
    void DoSomeOtherThing();
    void Dispose();
}

public class SomeClassWithMultipleInterfaces : ISomeDisposableThing, ISomeOtherDisposableThing
{
    public void Dispose() => /* called if class is disposed */;

    void ISomeDisposableThing.Dispose() => /* called if ISomeDisposableThing is disposed */;

    void ISomeOtherDisposableThing.Dispose() => /* called if ISomeOtherDisposableThing is disposed */;
}

public record DisposeCallingConsumer(
        ISomeDisposableThing interface1,
        ISomeOtherDisposableThing interface2,
        SomeClassWithMultipleInterfaces theClass)
{
    void DoStuff()
    {
        // (A record should not dispose like this, but just to keep the example code small and focused on the proposed syntax.)

        // Disposing via new proposed "dispose(...)" keyword that works with duck-typing similar to "foreach(...)":
        dispose(interface1);
        dispose(interface2);
        dispose(theClass);

        // In all calls above the implementing class knows what the caller (this) *thinks* it is disposing,
        // and can use explicit implementation to act accordingly.
    }
}

Alternative Designs

None.

Risks

  • What kind of dispose action should consumers expect when using the using keyword?
  • Should calling dispose when duck-typing cannot find a Dispose method at compile-time be a compile error, warning, or information? We are torn between how similar we want it to be to foreach and how similar we want it to be to using.
  • If a user updates their existing code by using the proposed dispose keyword, there is a small risk of behavioral change if they already had another Dispose method declared somewhere with the same signature as IDisposable.Dispose(). The good thing is that unless the user refactors their code to use dispose it shouldn't happen, but it does complicate possible code analyzers - i.e. if we wanted an analyzer to recommend a refactor to the user to call dispose instead, it would have to check that no duck-typed Dispose method aside from the method that IDisposable.Dispose would resolve to exists before it proposes the change.

Activity

  1. added
    api-suggestion
    on May 14, 2026
  2. added
    untriaged
    on May 14, 2026
  3. AnorZaken commented on May 14, 2026

    @AnorZaken
    Author

    Admittedly this proposal is just a draft.

    It doesn't show the full solution to the original problem, but it eliminates the first hard roadblock that prevents a full solution to be approached. More refinement is needed to come up with recommended usage and demonstrate how it can effectively solve the multi-inheritance dispose problem.

    But at the very least I propose we add the analyzer warning that checks for classes that implements IDisposable + at least two other interfaces. Such implementations probably exists in the wild and could be causing subtle dispose lifetime issues.

  4. huoyaoyuan commented on May 14, 2026

    @huoyaoyuan
    Member

    First, this is a C# language feature, not an API. It should be discussed at https://github.com/dotnet/csharplang/discussions.

    It remains problematic that when a disposable class implements multiple interfaces, the lifetime of those interfaces could be subtly different, affected by dispose call order

    This is not really a common practice. Lifetime is typically by instance, not interface. Since an object has only one constructor, it should be able to dispose its resource in a defined order.

    In conclusion the dispose pattern is subtly broken under multi-interface inheritance in C#, and in hindsight the only way to correctly implement dispose semantics would have been to use Duck-Typing just as foreach does: Add a dispose(...) keyword similar to foreach(...) have it resolve Dispose via Duck-Typing just like foreach: If an interface has a Dispose method, it compiles. Now the implementing class can implement differentiated Dispose methods via explicit interface implementation, which solves the broken dispose pattern.

    Why is a new language feature required at all? Just simply call interface1.Dispose() on the interface object.
    For using, it's already duck-typed for ref struct. The is a proposal to extend this to every type, but I can't find it currently.

  5. tannergooding commented on May 14, 2026

    @tannergooding
    Member

    In addition to what @huoyaoyuan said, the correct thing to do in this case is to "unify" the two dispose methods with yet another Dispose on the type that implements the other two and ensuring that it is properly cleaned up. The unifying type must understand the nuance of correct dispose order and is unsafe otherwise.

  6. removed
    untriaged
    on May 14, 2026
  7. AnorZaken commented on May 15, 2026

    @AnorZaken
    Author

    I apologize for posting this in the wrong place, but I also just want to say that it seems none of you opened the link to the other issue. And obviously I did a poor job explaining what the problem is, that much is apparent now, so I'm not blaming you guys, I just want to clarify what problem I was pointing at.

    The problem isn't about the object with multiple interfaces being able to dispose itself, that should be easy to implement.

    The problem arises one layer above this object, for the consumers of those interfaces. The example given in the link talks about how to do cleanup in the correct order when disposing a collection of service-provider objects kinda. You could say that to consumers they only see interfaces, and the normal thing to expect is that each interface represents different instances, usually. So by disposing one interface, any consumer of the other interface will be in a half-disposed state. This mostly just highlights that it's not really a good idea to inherit two disposable interfaces in a single implementation, which is why I'm thinking there should be an analyzer for this that warns against the risks.

    So yeah, having slept on it, I think mostly the analyzer is the better idea, and the other stuff that allows a user to potentially solve a problem they probably shouldn't have created in the first place... maybe not so important to support that.

    Again, sorry for posting in the wrong place though.

  8. huoyaoyuan commented on May 15, 2026

    @huoyaoyuan
    Member

    I've watched the linked issue closely before this issue, and voted for it. The linked comment doesn't seem to be related to the situation of this issue at all. DI is only related to IDisposable.Dispose, not SomeInterface.Dispose.
    The linked comment itself can hardly be an issue either.

  9. AnorZaken commented on May 15, 2026

    @AnorZaken
    Author

    I've watched the linked issue closely before this issue, and voted for it. The linked comment doesn't seem to be related to the situation of this issue at all. DI is only related to IDisposable.Dispose, not SomeInterface.Dispose.
    The linked comment itself can hardly be an issue either.

    Linked comment, quoted verbatin:

    Since the services are disposed in the reverse order (as they should), IGreetingGenerator will be disposed before ExampleNameRunner, which means ExampleNameRunner will hold a reference to a disposed singleton without itself having been disposed.

    The SP would need to dispose from interface side instead of implementation side of it's registered services. However since it was mentioned by Tanner that there are debates about using resolving via duck-typing already, then maybe we're not that far off - I wasn't aware of this, very interesting!

    The reason my idea doesn't map onto the linked problem directly is because I was trying to take a step back and look at a broader picture than just SP collections.
    Doesn't mean my idea was a brilliant one though. 😅

  10. tannergooding commented on May 15, 2026

    @tannergooding
    Member

    Resource disposal is complex and doing it correctly even more so, we have extensive documentation over how IDisposable needs to be implemented for this to be "safe/correct": https://learn.microsoft.com/en-us/dotnet/fundamentals/runtime-libraries/system-idisposable, https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-dispose#the-disposebool-method-overload, etc

    In general objects must be disposable in any order and need to allow the Dispose method to be called multiple times (doing nothing on subsequent calls, assuming it hasn't been reinitialized).

    Authors can of course technically implement Dispose however, but that would be in violation of the contract required by the interface.

  11. AnorZaken commented on May 15, 2026

    @AnorZaken
    Author

    Resource disposal is complex and doing it correctly even more so, we have extensive documentation over how IDisposable needs to be implemented for this to be "safe/correct": https://learn.microsoft.com/en-us/dotnet/fundamentals/runtime-libraries/system-idisposable, https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-dispose#the-disposebool-method-overload, etc

    In general objects must be disposable in any order and need to allow the Dispose method to be called multiple times (doing nothing on subsequent calls, assuming it hasn't been reinitialized).

    Authors can of course technically implement Dispose however, but that would be in violation of the contract required by the interface.

    Yes I agree, the linked problem is more a problem of life-time and the desire to avoid the situation where another object holds a reference to a disposed resource without knowing that it has already been disposed (i.e. the semi-disposes state). It's not that disposing itself would fail or become unsafe, it's that the second consumer would subsequently fail (because of the classic problem that it's never a good idea if a disposable object have shared ownership).

    In the context of Stream handling, this was solved by adding bool flags everywhere to consumers telling them if the should dispose their streams or not (essentially telling them they just "borrow" the Stream rather than own it). This isn't very elegant, but it works well enough mostly. In the specific case of SP though, we do not have access to any such mechanisms. The whole point of SP is to avoid instantiation of implementations, so we have no way to request a new non-disposed instance. In a sense it boils down to it being a bad idea to have any SP registered services that are disposable in the first place (unless they have transient lifetime).

  12. tannergooding commented on May 15, 2026

    @tannergooding
    Member

    Yes, users can write bugs and dispose of things that are still in use. It's in general a "use after free" problem and can represent a potential security or other issue. There's no really fixing this and the only real way is to push down a concept of "ownership" like Stream does -- and noting ownership semantics in the language mostly only work with unique references, shared references introduce a number of scenarios that keep it difficult to handle.

    Management of lifetimes is simply complex and things involving Dispose fundamentally include some management of lifetime.

  13. locked and limited conversation to collaborators on Jun 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionarea-TypeSystem-coreclr

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions