views:

246

answers:

3

Out of curiosity i disassembled mscorlib.dll to check the implementation of System.Object class.

I found something weird in that.

1).    
public class Object {
...
    protected override void Finalize(){}
...
}

How come a base class has an overriden method in it?

2) public class Employee {
            public void InstanceMethod() {
                this.Finalize();
                //Does not compile, can i not access protected methods of base class??
            }
        }

I am just wondering what's the use of "protected Finalize" method in Object class and why it has got special treatment by compiler?

A: 

Check out the MSDN to Object.Finalize:

Destructors are the C# mechanism for performing cleanup operations. Destructors provide appropriate safeguards, such as automatically calling the base type's destructor. In C# code, Object.Finalize cannot be called or overridden.

Therefore, an answer to your question would be: Well - that's part of the internals of the CLR; the C# compiler does all the work required when writing for example:

public class Employee
{
   //Finalizer, also known as "destructor"
   ~Employee()
   {

   }
}
winSharp93
+4  A: 

It is a bug in Reflector, it gets confused by a method that's virtual but doesn't have the "newslot" attribute and doesn't have a base class type. It might be easier to see when you switch the decompiler to IL.

The real declaration of the finalizer, as copied from the Reference Source, is much as you'd expect it to be:

// Allow an object to free resources before the object is reclaimed by the GC.
//
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
~Object()
{
}
Hans Passant
+1 for pointing out a bug in reflector. I always relied on it blindly :). It's wise to check for the IL directly while using reflector.
Amby
+1  A: 

For the second question, C#'s ~MyClass is written in VB.NET as Protected Overrides Sub Finalize() which is equivalent to protected override Finalize(). So it is just C# syntax difference.

For the first question, in Reflector it is

.method family hidebysig virtual instance void Finalize() cil managed

which is missing newslot attribute generally seen on new virtual members as compared to overridden.

Andrey Shchekin