Generating Dispose Pattern
Rider helps you automatically generate various implementations of IDisposable
depending on kind of resources that your class owns:
- If your class only owns managed
IDisposable
resources, Rider will help you generate a simple implementation ofpublic void Dispose()
without parameters, whereDispose()
is called on selected disposable members. - If your class only owns unmanaged resources, Rider will additionally generate destructor and a
ReleaseUnmanagedResources
method where you could write your cleanup code. - If your class owns or will potentially own (via inheritance) both managed and unmanaged resources, Rider will additionally create a
Dispose(bool disposing)
method which could be overridden by the inheritors.
To configure how the disposable pattern is implemented, use option in the Generate dialog.
In the example below, this command is used to generate a disposable pattern for managed logger
and resource
fields, with a single option to generate nullability checks for these fields.
To generate a dispose pattern
- In the editor, set the caret on the type name or within a type at the line where you want to insert a dispose pattern. If the caret is on the type name, generated code will be added in the beginning of the type declaration.
- Press Alt+Insert or choose in the main menu.
- In the Generate pop-up menu, select Dispose Pattern.
- In the Generate dialog that appears, you will see a list of private properties and fields of type assignable to
IDisposable
. Select some or all of these type members, and Rider will generate wrappers in the current type that delegate execution to selected type members.Optionally, use the following controls in the dialog:
- Fields can be null - appears if there are any nullable fields or properties in your type. By default, this check box is selected meaning that Rider will generate nullability checks for selected fields. You can clear this check box if you do not need nullability checks.
- I have unmanaged resources - if this check box is selected, Rider will additionally generate destructor and a
ReleaseUnmanagedResources
method where you could write your cleanup code. - I plan to inherit from this class - if this check box is selected, Rider will additionally create a
Dispose(bool disposing)
method which could be overridden by the inheritors. - Dispose already exists - appears if an implementation of
Dispose()
already exists and lets you choose whether to: - Destructor already exists - appears if you have chosen the I have unmanaged resources option and the class already has a destructor. Use this selector to choose whether to:
- Click OK to complete the wizard.
This action is also available as a quick-fix if IDisposable
is not implemented.
Last modified: 11 October 2017