Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are unmanaged objects?

Tags:

c#

What are unmanaged objects? Can you please explain it in terms of the CLR? I learned on the internet that they say unmanaged objects don't run under the CLR environment. Can you please give me an example of unmanaged objects?

like image 848
NoviceToDotNet Avatar asked Oct 31 '10 06:10

NoviceToDotNet


4 Answers

Any memory not managed by the CLR memory management (i.e. garbage collector) is unmanaged memory.

An OS file handle is one example of unmanaged memory (under .NET and windows).

To properly dispose of unmanaged resources, it is recommended that you implement a public Dispose or Close method that executes the necessary cleanup code for the object. The IDisposable interface provides the Dispose method for resource classes that implement the interface. Because it is public, users of your application can call the Dispose method directly to free memory used by unmanaged resources. When you properly implement a Dispose method, the Finalize method becomes a safeguard to clean up resources in the event that the Dispose method is not called.

Ref: Cleaning Up Unmanaged Resources

like image 71
Mitch Wheat Avatar answered Sep 28 '22 04:09

Mitch Wheat


In simple words, the unmanaged objects are the objects that aren't managed by the .Net framework.

Best example is the database connection or file operation are handled by the OS at the end and need to be liberated explicitly (File.Close() or Connection close) and won't be handled automatically by the Garbage collector.

like image 21
Zied Avatar answered Sep 28 '22 06:09

Zied


VC++6.0 samples or many of activeX and COM objects your using everyday for your application or website are unmanaged, for example Excel VBA is unmanaged and too many other samples.

like image 32
Saeed Amiri Avatar answered Sep 28 '22 05:09

Saeed Amiri


I learned on the internet that they say unmanaged objects don't run under the CLR environment.

This is not right, the CLR is pretty much able to do everything whats possible within C. In C# you have got a keywoard called unsafe which allows you to access even pointers and pointer offsets. I have a project where I do heavy Interop with a game engine and the C wrapper is so small, because I can handle all the memory objects within the CLR/C#.

By doesn't run they probably wanted to make it explicitly clear that the unamanged objects are not handled by the virtual machine: you have to do the cleanup or create wrapper classes which do the clean up for you.

like image 31
Andrius Bentkus Avatar answered Sep 28 '22 04:09

Andrius Bentkus