Skip to content

Auto-implemented IDisposable for classes with disposable fields. #111

@Mr-Byte

Description

@Mr-Byte

Currently, implementing IDisposable requires a significant amount of boiler plate code. I would like to propose a way to auto-implement IDisposable for fields. Using the following syntax:

public class Foo : IDisposable
{
    private using Bar _barResource;
}

Here the using keyword is being used as a modifier on the field. It indicates that the field should be disposed when the Dispose method is called. These fields would act the same way as readonly fields in that they can only be set from inside constructors or with field initializers.

This syntax would then have the compiler auto-implement IDisposable that handles disposing all fields marked using and also a finalizer to call Dispose if it has not yet been called. The above code sample would expand into the typical dispose pattern.

There are a few considerations that need to be made, though. These include, but are not limited to:

  • What to do with potential circular references between resources?
  • How to handle dispose logic that doesn't fit the typical pattern?
  • How to differentiate between managed and unmanaged disposable resources?

The value I could see this feature providing is a reduction in the amount of code needed to write classes that are composed of IDisposable resources to ensure proper cleanup of those resources.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions