-
Notifications
You must be signed in to change notification settings - Fork 4.2k
Description
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.