views:

157

answers:

4

Hello All

One of my friend told me that dynamic method is the only way if you want to at run time construct code that can be garbage collected.

One question in my mind that how garbage collector garbage the object which generated using reflection?

+4  A: 

An object constructed using reflection will be garbage collected like any other type of object, for example when it leaves the scope of a method if it's a method variable.

Gerrie Schenck
ok @@Gerrie Schenck but who will decide that code is manage or unmanaged? Is it decided by CRL?
Pankaj
Reflection is managed. And unmanaged resources will never be cleaned up by the garbage collector, since they don't live in the managed heap.
Gerrie Schenck
Thanks @@Gerrie Schenck, but again my question is that who decide that code is manage or unmaged
Pankaj
Any .NET object is managed in this context. If its written in a .NET language, compiled using a .NET compiler and lives within a .NET assembly...
Arjan Einbu
ya right. I don't understand the confusion here. If you create a managed type using reflection it will be handled by Garbage collector, an unmanaged type will be handled differently. Once the code is generated and loaded it behaves the same as any other .NET code.
A9S6
Really very-2 Thanks @@Arjan.. If i use some 3rd party .dll in my manage code, which consist of unmanaged code.In this condition my manage object will call unmanage dobject. That how CRL will handle this condition...
Pankaj
+1  A: 

how should an object created by reflection be different than one created normally?

you have an instance variable of this object... the runtime exactly knows what type of object it is, and also does the GC.

only the way the object is created is different. the object should be exactly the same as one created with new MyObject()

Atmocreations
+4  A: 

Garbage collection will collect any .NET objects. It doesn't differ wether they are created using reflection or not.

Arjan Einbu
Really very-2 Thanks @@Arjan.. If i use some 3rd party .dll in my manage code, which consist of unmanaged code.In this condition my manage object will call unmanage dobject. That how CRL will handle this condition...
Pankaj
To use .NET reflection and the CLR, the objects will need to at least have a .NET wrapper. GC cleans up after the wrappers, but the wrappers should clean up after themselves, maybe in the finalizer... I'd expect that this is taken care of with the COM wrappers created by .NET...
Arjan Einbu
Thanks @@Arjan...
Pankaj
A: 

Any piece of code that runs under the control of CLR is managed code and CLR governs and decides for garbage collection. there are ways in which you can coltrol the Garbage collection but unless it is really required let CLR decide.

Vinay Pandey