Auto-implemented IDisposable for classes with disposable fields.
See original GitHub issueCurrently, 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.
Issue Analytics
- State:
- Created 9 years ago
- Reactions:1
- Comments:8 (6 by maintainers)
Top GitHub Comments
I would lean towards:
The generated implementation of
Dispose(bool)
could be implemented in a manner where recursive calls are simply ignored.Probably in a manner similar to constructors. For example, the following doesn’t cause a problem:
There is no need to. Only allow this syntax on a field where the static type of the field is a type that implements
IDisposable
. These are always managed objects.We are unlikely to provide direct language support for this, however, we expect there will likely be solutions built on #5292/#5561.