What is meant by the terms managed resource and unmanaged resource in .NET? How do they come into the picture?
In the Q&A What are unmanaged resources?1, Bruce Wood posted the following:
I think of the terms "managed" and "unmanaged" this way:
"Managed" refers to anything within the .NET sandbox. This includes all .NET Framework classes.
"Unmanaged" refers to the wilderness outside the .NET sandbox. This includes anything that is returned to you through calls to Win32 API functions.
If you never call a Win32 API function and never get back any Win32 "handle" objects, then you are not holding any unmanaged resources. Files and streams that you open via .NET Framework class methods are all managed wrappers.
Comment: You may not be holding an unmanaged resource directly. However, you may be holding an unmanaged resource indirectly via a managed "wrapper class" such as System.IO.FileStream. Such a wrapper class commonly implements IDisposable (either directly or via inheritance).
...many managed (.NET Framework) objects are holding unmanaged resources inside them, and you probably want to Dispose() of them as soon as you can, or at least offer your callers the opportunity to do so. That's where writing your own Dispose() method comes in. Essentially, implementing IDisposable() does two things for you:
Allows you to get rid of any resources you grabbed directly from the operating system behind .NET's back (unmanaged resources).
Allows you and your callers to release hefty .NET objects / .NET objects that are holding precious resources in their grubby little hands that you / your callers want released now.
Comment: By implementing IDisposable
and thereby providing a Dispose()
method, you are enabling a user of your class to release in a deterministic fashion any unmanaged resources that are held by an instance your class.
1 Link originally shared in Sachin Shanbhag's answer. Quoted material dated 2005-11-17. Note that I have lightly copy-edited the quoted content.