Home > Net >  Can a class implementing IDisposable be a managed resource?
Can a class implementing IDisposable be a managed resource?

Time:08-01

I'm studying the standard Dispose pattern.

I'm looking at the example on MSDN and I have a question.

Looking at the example, there are the following parts.

...

// Other managed resource this class uses.
private Component component = new Component();

...

I learned that unmanaged resources should implement IDisposable.

The Component class implements IDisposable. But why a managed resource?

CodePudding user response:

If you create a class that implements IDisposable then instances of that class are managed resources. "Managed" basically means .NET. If you create a .NET class then it is managed by definition. Generally speaking, you implement IDisposable when your type holds references to other managed resources, i.e. instances of other .NET types that implement IDisposable, or unmanaged resources. Unmanaged resources are things that belong to the OS, like file handles, window handles, etc.

It's fairly rare that you will hold unmanaged resources directly but, for instance, it's possible that you might call a Windows API function that returns a handle retrieved directly from the OS that you need to explicitly release. More often, you will hold managed resources that are types from the framework itself and they will hold unmanaged resources, either directly or indirectly.

An example might be if you create a FileStream, which will hold a file handle internally. The FileStream is a managed resource and the file handle is an unmanaged resource. In that situation, your Dispose method would dispose the FileStream, i.e. clean up the managed resource, and it will clean up its own unmanaged resource.

  • Related