Garbage collection

Please explain how the garbage collector works in managed code.

The garbage collector checks to see if there are any objects in the heap that are no longer being used by the application. If such objects exist, then the memory used by these objects is reclaimed. When the garbage collector starts running, it makes the assumption that all objects in the heap are garbage. It assumes that none of the application's roots refer to any objects in the heap. The garbage collector starts walking the roots and building a graph of all objects reachable from the roots. Once all the roots have been checked, the garbage collector's graph contains the set of all objects that are somehow reachable from the application's roots, any objects that are not in the graph are not accessible by the application, and are therefore considered garbage. The garbage collector now walks through the heap linearly, looking for contiguous blocks of garbage objects. The garbage collector then shifts the non garbage objects down in memory (using the standard memory function), removing all of the gaps in the heap. Of course, moving the objects in memory invalidates all pointers to the objects. So the garbage collector must modify the application's roots so that the pointers point to the objects new locations. After all the garbage has been identified, all the non-garbage has been compacted, and all the non-garbage pointers have been fixed-up, the NextObjPtr is positioned just after the last non-garbage object.

What is reflection? Give an example of when you would want to use it.

Reflection in .NET makes it possible to explore the CLR type system programmatically. Reflection allows you to find what types are in an assembly, the methods of a type, how many arguments a method has, and so on.

In situations where we don't have access to a Dll until runtime or have no interface contract with any assembly etc., we can programmatically look up the supported properties and methods inside the assembly & then invoke any method at runtime.

Another example would be where I can write a small Test application that tests a Dll. I can use reflection apis to display a list of supported classes, properties and methods and my Test application can invoke each of this method programmatically.

What is a delegate?

A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked.

No comments: