A big bug in C# 1.0/1.1/2.0

L

Li jianzhong

First, look at the following code:

using System;

public class Grandpapa
{
~Grandpapa(){ Console.WriteLine
("Grandpapa.~Grandpapa");}
}

public class Parent:Grandpapa
{
~Parent(){ Console.WriteLine("Parent.~Parent");}
}

public class Son:parent
{
~Son(){ Console.WriteLine("Son.~Son");}
}

public class App
{
public static void Main()
{
Son s=new Son();

GC.Collect();
GC.WaitForPendingFinalizers();
}
}

The above code's output is :

Son.~Son
Parent.~Parent
Grandpapa.~Grandpapa

OK, no problem. But let's change the class Parent's
definition as fowllowing:

public class Parent:Grandpapa
{
protected void Finalize(){ Console.WriteLine
("Parent.Finalize");}
}


The output will be:

Son.~Son
Parent.Finalize

Very odd, right? Here is an odder one, change the class
Parent's definition as fowllowing:

public class Parent:Grandpapa
{
protected virtual void Finalize(){ Console.WriteLine
("Parent.Finalize");}
}


The output will be:

Grandpapa.~Grandpapa


Could you C# guys in Microsoft explain the odd output?

BTW, the output is same in .NET Framework 1.0/1.1/2.0
(Longhorn alpha version)?
 
P

Pete Davis

No, this more or less makes sense.

First of all, keep in mind that there's no guarantee a destructor (a.k.a.
Finalize(), since they're the same thing, almost) will EVER get called in
managed code.

Second of all, according to the documentation:

ms-help://MS.VSCC.2003/MS.MSDNQTR.2003OCT.1033/csref/html/vclrfClassDestruct
ors.htm

A destructor implicitly calls the base class Finalize(). It has to because a
base class can't take any method modifiers. The Finalize() methods you have
are incorrectly coded. They should have the override modifier because
Finalize() is a virtual method. You should then call the base class'
Finalize() method from the child's Finalize() method.

Pete
 
P

Pete Davis

I just read this over. Where it starts: "It has to because a base class..."
should be, "It has to because a destructor can't take any method modifiers."
sorry about that.

Pete
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top