Last Updated:

Managed code and Unmanaged code - Types | .Net

Managed type—A type of data that is initialized (usually using the new operator) in a managed dynamically allocated memory area, but by no means in an unmanaged dynamically allocated memory area or stack. Simply put, a managed type is a type for which garbage collection is performed automatically, so you do not need to use the delete operator to release resources used by objects of this type.

Instead of explicitly deleting an object, you can either make sure that no pointer points to it or explicitly equate the pointer to zero. Unmanaged type is a type that is ignored by the automatic garbage collector, so the programmer must free the memory occupied by the object using the delete operator.

Objects of unmanaged types are never created in a managed dynamically allocated memory area, but only either in an unmanaged dynamically allocated memory area or in some other memory location, like variables in a stack or data items of another unmanaged class. Therefore, unmanaged types are what C++ programmers are used to dealing with, whereas managed types are more like Java reference types that use automatic garbage collection.

The keyword _g c (short for "garbage collection") is used to declare managed classes, or structures, and can be used for pointers and arrays. The keyword _pode (short for "no garbage collection") is an antonym _g c (garbage collector). Keep in mind that the _g c (garbage collection) keyword can only be used in managed code, which means that you should use the /CLR (Compile to Run in Common Language) compiler option, and the Ipragma unman-aged pragma must be inactive. You can use the _nogc keyword (without garbage collection) in both managed and unmanaged code. The following snippet demonstrates the typical use of _g c (garbage collector) when defining a managed class:

_gc class Managed Class
// garbage collector class Managed Class
{
};

The _nogc keyword (without garbage collection) simply means that the class, structure, array, or object that the pointer defined with that word points to is not managed by the .NET garbage collector. This keyword is used to explicitly indicate that an object is never created in a manageable dynamically allocated memory area. You cannot inherit a type defined with the keyword _g c (garbage collector) or _nogc (no garbage collection) from a type defined with another of these keywords, just as you cannot use _g c (garbage collector) in unmanaged code.

_nogc class UnmanagedClass
{
};

Note that automatic garbage collection of managed objects is only concerned with freeing up unused managed dynamically allocated memory, but not other resources, such as file handles or database connections.