Implement IDisposable
- 2 minutes to read
Purpose
Using this Code Provider, you can easily make any class disposable. This Code Provider adds the IDisposable implementation along with all required methods (Dispose() and other optional methods) to the class.
Availability
It is available when the caret is in a class declaration.
Usage
Place the caret in a class declaration.
Note
The blinking cursor shows the caret’s position at which the Code Provider is available.
- Press the Ctrl + . or Ctrl + ~ shortcut to invoke the Code Actions menu.
- Select Implement IDisposable from the menu.
- Select the members to dispose of using the mouse or Space key.
Optionally, open the Options menu using the Ctrl key.
- To change options, use the mouse or corresponding letter keys displayed in the menu.
- To close the menu, hit Enter.
- Hit Enter to confirm the members’ selection.
After execution, the Code Provider implements the IDisposable interface and adds a common implementation of the required overloads.
Assuming that you have all available members selected (S1 and S2) and left all options disabled, the following code is generated:
public class DisposableClass : IDisposable {
public Stream S1;
public Stream S2 { get; set; }
public void Dispose() {
S1.Dispose();
S2.Dispose();
}
}
Options
Use the Options menu to configure the Code Provider.
You can change the following parameters by hitting the corresponding Key or by using your mouse:
Fields can be null
Key: N
Check this option if the fields or properties for which you are going to define the dispose pattern are null. If this option is selected, the members are checked for null before being disposed of.
Type can be inheritable
Key: I
Check this option to create another protected virtual Dispose method accepting a boolean parameter, which allows you to disable the actual disposing.
Type contains unmanaged resources
Key: U
Check this option to create the ReleaseUnmanagedResources method and the destructor that calls ReleaseUnmanagedResources and optionally calls Dispose.