shinu


Hi,

We all know that Finalize is a protected method.But it can be called by CLR GC.
Can anyone explain this


Thanks in advance..






Re: Visual C# Language How CLR can call Finalize as it is a protected method

Peter Ritchie

Anyone can call a protected method if they know it's name by reflecting on it to get a MethodInfo object, then calling Invoke.






Re: Visual C# Language How CLR can call Finalize as it is a protected method

Nimrand

Peter is right, although to do that the code needs certain CodePermissions. Since code is often run as fully trusted this isn't usually an issue.

That said, I don't want you to think that the CLR GC is using reflection to call the finalizer. I'm pretty sure thats not the case. The reason that private/protected methods cannot be called is because the language compilers wont compile such code, and even if they did, the CLR will not allow the call when it JIT-compiles the code. However, the CLR can certainly allow itself to call protected/private methods, which is essentially what its doing when it calls the finalizer.





Re: Visual C# Language How CLR can call Finalize as it is a protected method

Peter Ritchie

Yes, the CLR certainly doesn't use reflection to invoke the finalizers. Since the CLR is managing the vtables of methods for object, it inherently has access to that information. I was was just trying to show that being "protected" doesn't really offer a strict access guarantee.






Re: Visual C# Language How CLR can call Finalize as it is a protected method

Nimrand

Peter Ritchie wrote:

I was was just trying to show that being "protected" doesn't really offer a strict access guarantee.



I realized that, I just wanted to clarify so the original poster wouldn't misunderstand.




Re: Visual C# Language How CLR can call Finalize as it is a protected method

Rudrarup

U can use

Collect() method

http://msdn2.microsoft.com/en-us/library/xe0c2357.aspx